Running threads in fixed order in java

Reading Time: 2 minutes

When you are being interviewed for java, it is a common question when it comes to multi-threading. Some of the variants you might have come across like:

  • There are two different threads running simultaneously. 1st thread prints 0s while 2nd prints 1s. Write a program which prints 0s and 1s such that no two 0s and no two 1s are adjacent.
  • There are three different threads running simultaneously. Each thread only prints 1s, 2s and 3s respectively. Write a program to produce an output similar to 1-2-3-1-2-3-1-2-3…
  • Write a program that prints 0 to 100 in order with 2 threads, each printing one number in alternating order.

This kind of thread-alternating problems can be solved simply through wait-notify construct. Here’s an example in which one thread prints even number while other thread prints odd number. Thus the out put of program prints whole numbers in order.

First, we create a counter class, which will generate the numbers in order. This counter will be shared across the thread, thus this can also act as a lock.

class Counter {
	int x;

	public int get() {
		return x;
	}

	public void increment() {
		x++;
	}
}

The thread which will print even numbers.

class ThreadEven extends Thread {
	private Counter c;
	public ThreadEven(Counter c) {
		this.c = c;
	}

	public void run(){
		while(c.get() <= 100)
		synchronized(c) {	
			if(c.get() % 2 == 0) {
				System.out.println(c.get());
				c.increment();
				c.notifyAll();
			} else {
				try {
					c.wait();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

Another thread which will print odd numbers

class ThreadOdd extends Thread {
	private Counter c;
	public ThreadOdd(Counter c) {
		this.c = c;
	}

	public void run(){
		while(c.get() <= 100)
		synchronized(c) {	
			if(c.get() % 2 != 0) {
				System.out.println(c.get());
				c.increment();
				c.notifyAll();
			} else {
				try {
					c.wait();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

And finally, the driver code.

class AlternatingThreads {

	private static Counter counter = new Counter();

	public static void main(String[] s) {
		ThreadEven t1 = new ThreadEven(counter);
		ThreadOdd t2 = new ThreadOdd(counter);
		t1.start();
		t2.start();
	}
}

Leave a Reply