Join is not working. I get a wrong output. Here is the code:
package Test;
public class Test {
public static void main(String[] args){
System.out.println("Hello world!");
ThreadTest t1 = new ThreadTest("1");
ThreadTest t2 = new ThreadTest("2");
t1.start();
try{
t1.join();
System.out.println("OK!");
}catch( Exception e){
e.getMessage();
System.out.println("Fail!");
}
t2.start();
}
}
package Test;
public class ThreadTest extends Thread{
private Thread t;
private String name;
ThreadTest (String name){
this.name = name;
}
public void run(){
for(int i = 0; i<=10; i++){
System.out.println("Tread: " + name + " " + i);
}
}
public void start(){
if(t == null){
t = new Thread(this, name);
t.start();
}
}
}
I get the following output:
Hello world!
OK!
Tread: 1 0
Tread: 1 1
Tread: 1 2
Tread: 1 3
Tread: 1 4
Tread: 2 0
Tread: 2 1
Tread: 2 2
Tread: 1 5
Tread: 2 3
Tread: 1 6
Tread: 2 4
Tread: 1 7
Tread: 2 5
Tread: 1 8
Tread: 2 6
Tread: 1 9
Tread: 2 7
Tread: 1 10
Tread: 2 8
Tread: 2 9
Tread: 2 10
This is wrong! Thread 2 should start after thread 1 finished and not in between, because of the join() method.
What the other answers tell you is that your program creates four Thread instances, but it only uses two of them as threads. The Thread instance that you join is one of the two that your program never starts.
Part of your confusion is due to the fact that your Thread subclass has a method named start(), but that method doesn't do what Thread.start() does.
OK, that's all bad, but here's a deeper problem:
Q: What's the point of doing this:
Thread t = new Thread(...);
t.start();
t.join();
A: There is no point in doing that. The point of using threads---the entire point---is that when one thread starts another thread, the first thread can then do something else while the new thread is running:
Thread t = new Thread(...);
t.start();
doSomethingElse(...)
t.join();
You're not joining on the Thread, but on the object ThreadTest.
The method start is creating a new Thread and start it.
I suggest to add a method like this in ThreadTest and call it:
public void joinThread(){
if(t != null){
t.join();
}
}
You are creating a new Thread in this method
public void start(){
if(t == null){
t = new Thread(this, name);
t.start();
}
}
It should be like this
public class ThreadTest extends Thread{
ThreadTest (String name){
super(name);
}
public void run(){
for(int i = 0; i<=10; i++){
System.out.println("Tread: " + getName() + " " + i);
}
}
}
//t.join (10000) add a value large, so that t1 job is over
try{
t1.join(10000);
System.out.println("OK!");
}catch( Exception e){
e.getMessage();
System.out.println("Fail!");
}
Related
This question already has answers here:
Java. The order of threads execution
(2 answers)
Closed 3 years ago.
Thread two is running first on output though I've called start() method of thread1 at first. Why this is happening?
Output:
Thread two running: 0
Thread two running: 1
Thread one running: 0
Thread two running: 2
....
package interfacetest;
class thread1 extends Thread {
public void run() {
for(int i=0; i<10; i++) {
System.out.println("Thread one running: " +i);
}
}
}
class thread2 extends Thread {
public void run() {
for(int j=0; j<10; j ++) {
System.out.println("Thread two running: " +j);
}
}
}
class InterfaceTest {
public static void main(String[] args) {
thread1 t1 = new thread1();
thread2 t2= new thread2();
t1.start();
t2.start();
}
}
When we start thread, java starts execution of run method in separate thread. And thread ordering is never gauranteed. Here as you are simply starting 2 different threads no gaurantee that they will be executed in sequence.
Suppose I have 10 threads that are incrementing a variable by 1. Suppose Thread-1 increments a variable first, and then Thread-2 and Thread-3 and consecutively. after all the 10 Threads have incremented the variable. I need to decrement the same variable in a manner.
Decrementing, if Thread-1 incremented the variable first of all, then it should decrement at last.
We need to do this without setting thread priority.
you can use a lot of ways, here's one for example:
public class Main {
public static void main(String[] args) throws Exception {
for(int i=0;i<10;i++){
final int _i=i;
Thread t = new Thread(new T(_i));
t.start();
}
}
public static class T implements Runnable{
int threadNumber;
public T(int threadNumber) {
this.threadNumber=threadNumber;
}
#Override
public void run() {
increase(this);
}
}
static Thread[] threads = new Thread[10];
static int number =0;
static Object generalLock=new Object();
public static void increase(T t){
int myNumber=0;
synchronized (generalLock){
myNumber=number;
System.out.println("i am "+number+" incrementing, my real number "+t.threadNumber);
threads[number]=Thread.currentThread();
number++;
}
while (threads[9]==null){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i=9;i>myNumber;i--){
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized (generalLock){
System.out.println("i am "+number+" decrementing, my real number "+t.threadNumber);
number--;
}
}
}
output example:
i am 0 incrementing, my real number 1
i am 1 incrementing, my real number 8
i am 2 incrementing, my real number 9
i am 3 incrementing, my real number 7
i am 4 incrementing, my real number 6
i am 5 incrementing, my real number 5
i am 6 incrementing, my real number 0
i am 7 incrementing, my real number 4
i am 8 incrementing, my real number 3
i am 9 incrementing, my real number 2
i am 9 decrementing, my real number 2
i am 8 decrementing, my real number 3
i am 7 decrementing, my real number 4
i am 6 decrementing, my real number 0
i am 5 decrementing, my real number 5
i am 4 decrementing, my real number 6
i am 3 decrementing, my real number 7
i am 2 decrementing, my real number 9
i am 1 decrementing, my real number 8
i am 0 decrementing, my real number 1
Note: you can use simple Runnable, I create T class to show the thread number in order to print it while incrementing/decrementing
This seems to work. Essentially I create the 10 threads and specially identify one of them using an enum. They all try to increment the shared integer, identifying themselves. The incrementer detects the first increment by noticing the transition to 1 and if it's a Special thread it returns true .
There's also a CountDownLatch used to synchronise all of the threads to ensure there is at least a chance of the two alternatives. I get about 8600 out of the 10000 test runs where the Special got there first. This value will vary depending on many variables.
enum Who {
Special, Normal;
}
class PriorityIncrementer {
final AtomicInteger i = new AtomicInteger(0);
boolean inc(Who who) {
return i.incrementAndGet() == 1 && who == Who.Special;
}
public void dec() {
i.decrementAndGet();
}
}
class TestRunnable implements Runnable {
final Who me;
final PriorityIncrementer incrementer;
final CountDownLatch latch;
public TestRunnable(PriorityIncrementer incrementer, CountDownLatch latch, Who me) {
this.incrementer = incrementer;
this.latch = latch;
this.me = me;
}
#Override
public void run() {
// Wait for all others to get here.
latch.countDown();
try {
// Wait here until everyone os waiting here.
latch.await();
// Do it.
if(incrementer.inc(me)) {
// I was first and special, decrement after.
incrementer.dec();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private boolean test(int count) throws InterruptedException {
Thread[] threads = new Thread[count];
// The shared incrementer.
PriorityIncrementer incrementer = new PriorityIncrementer();
// Arrange for all of them to synchronise.
CountDownLatch latch = new CountDownLatch(threads.length+1);
// One special.
threads[0] = new Thread(new TestRunnable(incrementer, latch, Who.Special));
// The rest are normal.
for(int i = 1; i < threads.length; i++) {
threads[i] = new Thread(new TestRunnable(incrementer, latch, Who.Normal));
}
// Start them up.
for (Thread thread : threads) {
thread.start();
}
// Wait a moment.
Thread.sleep(1);
// Start them all going.
latch.countDown();
// Wait for them to finish.
for (Thread thread : threads) {
thread.join();
}
// Who won?
return incrementer.i.get() < count;
}
public void test() throws InterruptedException {
final int tests = 10000;
int specialWasFirstCount = 0;
for (int i = 0; i < tests; i++) {
if(test(10)) {
specialWasFirstCount += 1;
}
}
System.out.println("Specials: "+specialWasFirstCount+"/"+tests);
}
Synchronization works correctly in this code:
class PrintNumbers {
synchronized public void display() {
System.out.println("in display");
for (int i = 0; i < 3; i++) {
System.out.println("Thread name : "+ Thread.currentThread().getName() + " i= " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.getMessage();
}
}
System.out.println("out of display");
}
}
class MyThread implements Runnable {
Thread t;
PrintNumbers printNumbers;
MyThread(PrintNumbers printNumbers, String s) {
this.printNumbers = printNumbers;
t = new Thread(this,s);
t.start();
}
public void run() {
printNumbers.display();
}
}
class SyncExample {
public static void main(String[] args) {
PrintNumbers printNumbers = new PrintNumbers();
new MyThread(printNumbers, "My Thread 1");
new MyThread(printNumbers, "My Thread 2");
}
}
Output:
in display
Thread name : My Thread 1 i= 0
Thread name : My Thread 1 i= 1
Thread name : My Thread 1 i= 2
out of display
in display
Thread name : My Thread 2 i= 0
Thread name : My Thread 2 i= 1
Thread name : My Thread 2 i= 2
out of display
but not in this code:
class PrintNumbers {
synchronized public void display() {
System.out.println("in display");
for (int i = 0; i < 3; i++) {
System.out.println("Thread name : "+ Thread.currentThread().getName() + " i= " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.getMessage();
}
}
System.out.println("out of display");
}
}
class MyThread implements Runnable {
Thread t;
PrintNumbers printNumbers;
MyThread(String s) {
this.printNumbers = new PrintNumbers();
t = new Thread(this,s);
t.start();
}
public void run() {
printNumbers.display();
}
}
class SyncExample {
public static void main(String[] args) {
new MyThread("My Thread 1");
new MyThread("My Thread 2");
}
}
Output:
in display
Thread name : My Thread 1 i= 0
in display
Thread name : My Thread 2 i= 0
Thread name : My Thread 1 i= 1
Thread name : My Thread 2 i= 1
Thread name : My Thread 2 i= 2
Thread name : My Thread 1 i= 2
out of display
out of display
I cannot understand what difference wrt Synchronization does it make to initialize PrintNumbers in the Runnable MyThread and in the SyncExample class. Please explain.
I cannot understand what difference wrt Synchronization does it make to initialize PrintNumbers in the Runnable MyThread and in the SyncExample class.
It doesn't. What does matter is that in your first example, you have only one PrintNumbers instance which both threads share. But in your second example, you have two separate PrintNumbers instances, one for each thread.
Since PrintNumbers#display synchronizes on the instance (synchronized instance methods synchronize on this), it only synchronizes within the instance, not across multiple instances.
When both threads share an instance, the two calls to display are serialized. But when the threads each have their own instance, the two calls to display are on separate instances, and thus there is no serialization of the calls, they can overlap.
Because in the second code each thread has its own PrintNumbers object so they work in parallel. In the first one they share the single PrintNumbers object and work with it in synchronized way.
PS.
Remember that synchronized for non-static methods makes synchronization on object (for static methods on class).
It is working in both cases as it should. The difference is that in the first case you have a single object that is synchronized. In to second one you have two. They both are called only once so they are synchronized perfectly.
synchronized doesn't work between objects, only within one.
I'm working on the following assignment:
Consider a shared counter whose values are non-negative integers,
initially zero. A time-printing thread increments the counter by one
and prints its value each second from the start of execution. A
message-printing thread prints a message every fifteen seconds. Have
the message-printing thread be notified by the time-printing thread as
each second passes by. Add another message-printing thread that prints
a different message every seven seconds. Such addition must be done
without modifying the time-printing thread implementation.
Have all involved threads share the counter object that is updated by
the time-printing thread every second. The time-printing thread will
notify other threads to read the counter object each time it updates
the counter, then each message-printing thread will read the counter
value and see if its assigned time period has elapsed; if so, it will
print its message.
import java.lang.Class;
import java.lang.Object;
public class Main2 {
public static void main(String... args)
{
Thread thread = new Thread()
{
public void run()
{
int x = 0;
while(true)
{
x = x + 1;
System.out.print(x + " ");
if(x%7 == 0)
{
System.out.println();
System.out.println("7 second message");
}
if(x%15 == 0)
{
System.out.println();
System.out.println("15 second message");
}
try { Thread.sleep(1000); }
catch (Exception e) { e.printStackTrace(); }
}
}
};
thread.start();
}
}
This outputs what I want it to, but the requirement calls for multiple threads to output when the 7 and 15 second messages show. I can't wrap my head around how to use multiple threads to do this.
You have to remove the ";" after if conditions.
if(x%7 == 0);
and
if(x%15 == 0);
Check the following code
public static void main(String... args) {
Thread thread = new Thread() {
public void run() {
int x = 0;
while (true) {
x = x + 1;
System.out.print(x + " ");
if (x % 7 == 0)
{
System.out.println();
System.out.println("7 second message");
}
if (x % 15 == 0)
{
System.out.println();
System.out.println("15 second message");
}
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
thread.start();
}
My output for this as follows
1 2 3 4 5 6 7
7 second message
8 9 10 11 12 13 14
7 second message
15
15 second message
16 17 18 19 20 21
7 second message
22 23 24 25 26 27 ...
I just started learning "multithreading" in JAVA and it seams I don't understand how keyword "synchronized" works.
I had four examples and they're very alike (in my opinion), and I don't understand why I get every time different results.
public class BufferThread1 {
static int counter = 0;
static StringBuffer s = new StringBuffer();
public static void main(String args[]) throws InterruptedException {
new Thread() {
public void run() {
synchronized (s) {
while (BufferThread1.counter++ < 3) {
s.append("A");
System.out.print("> " + counter + " ");
System.out.println(s);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(BufferThread1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
Thread.sleep(100);
while (BufferThread1.counter++ < 6) {
System.out.print("< " + counter + " ");
s.append("B");
System.out.println(s);
}
}
}
Result:
run:
> 1 A
< 2 > 3 AA
AAB
< 5 AABB
< 6 AABBB
public class BufferThread2 {
static int counter = 0;
static StringBuilder s = new StringBuilder();
public static void main(String args[]) throws InterruptedException {
new Thread() {
public void run() {
synchronized (s) {
while (BufferThread2.counter++ < 3) {
s.append("A");
System.out.print("> " + counter + " ");
System.out.println(s);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(BufferThread2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
Thread.sleep(100);
while (BufferThread2.counter++ < 6) {
System.out.print("< " + counter + " ");
s.append("B");
System.out.println(s);
}
}
}
Result:
run:
> 1 A
< 2 AB
< 3 ABB
< 4 ABBB
< 5 ABBBB
< 6 ABBBBB
public class BufferThread3 {
static int counter = 0;
static StringBuffer s = new StringBuffer();
public static void main(String args[]) throws InterruptedException {
new Thread() {
public void run() {
synchronized (s) {
while (BufferThread3.counter++ < 3) {
s.append("A");
System.out.print("> " + counter + " ");
System.out.println(s);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(BufferThread3.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}.start();
Thread.sleep(100);
synchronized (s) {
while (BufferThread3.counter++ < 6) {
System.out.print("< " + counter + " ");
s.append("B");
System.out.println(s);
}
}}
}
Result:
run:
> 1 A
> 2 AA
> 3 AAA
< 5 AAAB
< 6 AAABB
Of course, I skipped
import java.util.logging.Level;
import java.util.logging.Logger;
I just don't realise how these examples work and synchronized here !
I do hope that someone help me.
Your < and > label which thread is running here.
> 1 A
Your background thread is running only and prints this line as expected.
< 2
The main thread prints the counter 2 but cannot acquire the lock on s so it blocks.
> 3 AA
The background thread increments the counter again and prints 3 and a second A. On the next iteration it exits and counter == 4 As the thread exits, it releases the lock.
AAB
The main thread can now acquire the lock and append("B")
< 5 AABB
The main thread increments the counter to 5 and adds another B
StringBuffer is a pet hate of mine which was replaced more thna ten years ago by StringBuidler. It is almost impossible to implement a useful thread safe class using it and when people have tried, it has meant the class wasn't really thread safe. Note: SimpleDateFormat uses StringBuffer and it is not thread safe.
Let's try a simpler example that gets at what synchronized does without such an overly complicated class.
Consider the following Runnable task:
public class Task implements Runnable {
private final int id;
public Task(int id) {
this.id = id;
}
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println("Task " + id + " prints " + i);
}
}
}
Then let's try running it with this main method:
public static void main(String[] args) {
Thread t1 = new Thread(new Task(1));
Thread t2 = new Thread(new Task(2));
t1.start();
t2.start();
}
The output could look something like this:
Task 1 prints 0
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
Task 2 prints 0
Task 2 prints 1
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
But it could also look like this:
Task 1 prints 0
Task 2 prints 0
Task 2 prints 1
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
Task 2 prints 4
The truth is, you have no guarantees about the order in which the two Tasks execute commands (with respect to each other. You still do know that each task will print 0...4 in order). The fact that t1.start() comes before t2.start() means nothing.
The synchronized command allows for some control over which thread executes when. Essentially, the command synchronized(obj) {....} means that at most one thread is allowed to execute the commands in the block (within the {...}) at a time. This is know as mutual exclusion.
A nice way to think about it is as a locked room with a single key hanging outside on the wall. In order to get into the room, you have to take the key off the wall, unlock the door, go into the room, and lock it from the inside. Once you are done doing whatever you are doing in the room, you unlock the door from the inside, go outside, lock the door from the outside, and hang the key up. It is clear that while you are in the room no one else can join you, as the door is locked and you currently hold the only key to get in.
To illustrate, consider the following improved task class:
public class SynchronizedTask implements Runnable {
private final Object lock;
private final int id;
public Task(int id, Object lock) {
this.id = id;
this.lock = lock;
}
public void run() {
synchronized(lock) {
for(int i = 0; i < 5; i++) {
System.out.println("Task " + id + " prints " + i);
}
}
}
}
And run it with the following modified main method:
public static void main(String[] args) {
Object lock = new Object();
Thread t1 = new Thread(new Task(1, lock));
Thread t2 = new Thread(new Task(2, lock));
t1.start();
t2.start();
}
We still don't know whether t1 or t2 will enter the synchronized block first. However, once has entered, the other must wait for it to finish. Thus, there are exactly two possible outputs of this code. Either t1 gets in first:
Task 1 prints 0
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
Task 2 prints 0
Task 2 prints 1
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
Or t2 gets in first:
Task 2 prints 0
Task 2 prints 1
Task 2 prints 2
Task 2 prints 3
Task 2 prints 4
Task 1 prints 0
Task 1 prints 1
Task 1 prints 2
Task 1 prints 3
Task 1 prints 4
It is important to note that this behavior only worked as desired because we used the same lock object for both Tasks. If we had run the following code instead:
public static void main(String[] args) {
Thread t1 = new Thread(new Task(1, new Object()));
Thread t2 = new Thread(new Task(2, new Object()));
t1.start();
t2.start();
}
We would have identical behavior to the original un-synchronized code. This is because we now have a room with two (or really, infinite if we replicate our thread initialization) keys hanging outside. Thus while t1 is inside the synchronized block, t2 can just use its own key to get in, defeating the whole purpose.
First example shown by Mr. Lawrey.
In the second example the "Background" thread only gets to do one print of and since StringBuilder is used this time instead of StringBuffer the main thread will not block while trying to print "s", hence only 1 A.
In the third example the main thread is blocked until the background thread terminates because you start the background thread before the main thread's loop. Thus the background thread will get 3 loops done and hence the 3 A's.
Though I suspect these are artificial examples for learning purposes it should still be noted that sleeping inside a synchronized block is NOT a good idea as this will not release the lock.