This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
this is from: SCJP 6 Mock exam for Threads � Niko�s java blog.mht
if line 1 is commented then answer is 0, otherwise it is 999999. what join() is doing here? i know that join method of thread lets one thread to join onto the end of another thread. Here when start is called on Job instance, then run method is invoked and after completion of that method thread.join() should be called. how this code is working?
in a thread(let's name it t1) you create a thread instance(let's name it t2). then you start that thread t2. then in t1, if you want something to be executed only when t2, then you call t2.join. The call will only return when t2 completes execution. So the execution of t1 will stop or pause till t2 completes.
What is happening is, Thread.join() method joins the current thread(Main in this case) with the previously started thread.
So what happens is, Main method waits for the previously started thread to complete. After the thread completes, main method continues to execute.
When you comment Thread.join(), what happens is, two parallel thread starts running(Main thread and the thread printing numbers in this case) and they execute without waiting for each other.
Following example might help to understand the issue you are having.
class Job implements Runnable { private int number = 0;
public void run() { for (int i = 0; i < 1000000; i++) { synchronized (this) { this.number++; } } }
public int getNumber() { return number; } }
public class Test { public static void main(String[] args) throws Exception { Job job = new Job();
Thread t1 = new Thread(job, "t1"); Thread t2 = new Thread(job, "t2"); Thread t3 = new Thread(job, "t3");
t1.start();// at this point we have main thread and t1 t2.start();// so far we have main thread, t1 and t2 t3.start();// now we have total 4 threads which are main, t1, t2 and t3
// join/append Thread t1 at the end of main thread // this would leave us total 3 thread main, t2 and t3 //t1.join();
// join/append Thread t2 at the end of main thread // and this would leave main thread and t3 //t2.join();
// join/append Thread t3 at the end of main thread // this would leave only main thread //t3.join();
// making sure to print the number after finished three threads t1, t2, t3 while (true) { if ((t1.getState() == Thread.State.TERMINATED) && (t2.getState() == Thread.State.TERMINATED) && (t3.getState() == Thread.State.TERMINATED)) { // If this.number incrementation is not synchronized in run method, // it is not guaranteed to satisfy number == 3000000 System.out.println(job.getNumber()); break; } } } }
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.