Threads in Java
Date: Mar 2013
Level: Advanced


INTERVIEW QUESTIONS

Company: IBM
Question Title: Threads in Java
Language: Java
QUESTION DETAILS:

Using two threads you have to print "Hello World Hello World Hello World Hello World Hello World Hello World ".
Out of the two threads, one should print "Hello" and another thread should print "World".


Here's the code:
public class HelloWordTwoThread {
	public class ThreadRunner {
		Object lock = new Object();
		boolean printHello = true;
		int counter = 5;
		Thread helloPrinter = new Thread() {
			@Override
			public void run() {
				while (counter > 0) {
					synchronized (lock) {
						while (!printHello) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								System.err.println("Interrupt Exteption!");
							}
						}
						if (counter > 0) {
							System.out.print("Hello");
						}
						printHello = false;
						lock.notify();
					}
				}
			}
		};
		
		Thread worldPrinter = new Thread() {
			@Override
			public void run() {
				while (counter > 0) {
					synchronized (lock) {
						while (printHello) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								System.err.println("Interrupt Exteption!");
							}
						}
						
						if (counter > 0) {
							System.out.println(" World");
						}
						
						printHello = true;
						counter --;
						lock.notify();
					}
				}
			}
		};	
		
		public void writeHelloWorl() {
			helloPrinter.start();
			worldPrinter.start();
			
			try {
				helloPrinter.join();
				worldPrinter.join();
			}catch (InterruptedException e) {
				System.err.println("Interrupeted while Joining!");
			}
		}
	}
	
	public static void main(String[] args) {
		new HelloWordTwoThread().new ThreadRunner().writeHelloWorl();
	}
}
All Questions