Hemlata Hemlata - 1 month ago 18
Java Question

Why threads are not working?

Here is my following code:

private int counter = 0;

public void incC() {
counter++;
System.out.println("Counter is: "+counter + " "+Thread.currentThread().getName());
}

public void printC() {
System.out.println("Counter is: "+counter + " "+Thread.currentThread().getName());
}

public static void main(String args[]) throws Exception {
Stuff stuff = new Stuff();

Thread t1 = new Thread(() -> {
stuff.incC();
});

Thread t2 = new Thread(() -> {
stuff.printC();
});

t1.start();
t2.start();

t1.join();
t2.join();
}
}


Here's my output:

Counter is: 1 Thread-1
Counter is: 1 Thread-0



  • Here
    t1.join()
    is called first. So shouldn't thread
    t2
    should wait for thread
    t1
    to die?

  • How's it possible for thread
    t2
    to output first before
    t1
    ?


Answer

t1.join() makes the current thread wait for thread t1 to die. It has no effects on the timing of any other thread but the current one. You have started two threads and they will run concurrently with no ordering constraints.

I should also note that starting two threads only to have one wait for the other's death defeats the purpose of multithreading.

Comments