Threads in Java
Date: Oct 2012
Level: Advanced


INTERVIEW QUESTIONS

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

Given four resources A1, A2, B1, B2 such that Thread T1 and Thread T2 operates on A1, A2 and B1, B2 respectively. How will you ensure the order of execution is A1-B1-A2-B2?


Here's the code:
   import java.util.concurrent.Semaphore;

public class ThreadAlternate {

	public static void main(String[] args) {
		String[] s1 = {"A1","A2","A3"};
		String[] s2 = {"B1","B2","B3"};
		MyThread t1 = new MyThread(s1, true);
		MyThread t2 = new MyThread(s2, false);
		t1.start();
		t2.start();
	}

}

class MyThread extends Thread{

	static Semaphore s1 = new Semaphore(1);
	static Semaphore s2 = new Semaphore(1);
	boolean flag = false;
	static{
		try {
			s2.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	String[] arr;
	public MyThread(String[] strArray, boolean flag) {
		this.arr = strArray;
		this.flag = flag;
	}

	public void run() {
		for (int i = 0; i < arr.length; i++) {
			if(flag){
				try {
					s1.acquire();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.err.println(arr[i]);
				s2.release();
			}else{
				try {
					s2.acquire();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				System.err.println(arr[i]);
				s1.release();
			}
		}

	}
}
All Questions