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 –

An example depicting sleep and join operations.

package com.kamalmeet;

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

		Thread t2 = new Thread(r);

		try {
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
		System.out.println("Exiting main thread now");

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