Thursday, November 29, 2012

Threads in java

Problem 1:
You have thread T1, T2 and T3, how will you ensure that thread T2 start after the end of T1 and thread T3 will start after T2 end?
Solution:
By using Thread.join();
     t1.start(); 
     t1.join(); 
     t2.start(); 
     t2.join(); 
     t3.start(); 
//     t3.join();  - not needed


Problem 2:
"You have T1, T2, and T3. T1 and T2 can execute concurrently, but T3 has to wait for both of them before it can run."
Solution:
     t1.start(); 
     t2.start(); 
     t1.join(); 
     t2.join(); 
     t3.start();
 

Compare wait and sleep methods in java
Wait release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

Wait is defined in Object class, where sleep methods are defined in Thread class.

Both could throw InterruptedException.


No comments:

Post a Comment