Thread Basics: Sleep, Join and Yield

When dealing with Java threads, some basic concepts can come handy in order to manage control among threads.

Sleep: A simple command which will tell the thread to go to sleep for given milliseconds. e.g. Thread.sleep(1000), tells current thread to wait for one second.

Join: This command tells program to wait till my current thread is done (killed). It has two versions. t1.join(), tells current thread to wait till thread T1 is killed before moving to next statement. A second verion takes milliseconds as input, t1.join(2000) tells current thread to wait till t1 is killed or 2 seconds which ever occurs first.

Yield: Yield is used by a thread to voluntarily give up control in favor of other threads. Though this is not guranteed- read more – http://www.javamex.com/tutorials/threads/yield.shtml

An example depicting sleep and join operations.

public class thread {

public static void main(String s[])
{
RunnableTest r=new RunnableTest();

Thread t1=new Thread(r);
t1.setName("t1");
t1.start();

Thread t2=new Thread(r);
t2.setName("t2");
t2.start();

try {
t1.join();
t2.join(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("EXiting main thread now");
}

}

class RunnableTest implements Runnable{
int count=0;
public synchronized void test()
{
try {
count++;
Thread.sleep(4000); //This will just introduce some delay
System.out.println(Thread.currentThread().getName()+" says Hello from Runnable:"+count);
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void run() {
test();
}
}