`

企业牛逼面试题目 高手进来讨论答题

阅读更多
1.给你两个正方体同0到9十个数字,能不能组成1个月中的日期,给出理由

2.你认为最快的排序的程序是什么,给出代码

3.设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
分享到:
评论
1 楼 fayedShih 2011-10-27  
第三题,不知道对不对
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Data {
	private int iPool = 0;
	private boolean pauseAdd = false;
	private int max=200;

	synchronized void add() {
		System.out.println("iPool in add() is " + ++iPool);
		if (iPool > max) {
			notifyAll();// notify other suspended task
			pauseAdd = true;
		}
	}

	synchronized void subtract() {
		System.out.println("iPool in minus() is " + --iPool);
		if (iPool < 0) {
			notifyAll(); // notify other suspended task
			pauseAdd = false;
		}
	}

	synchronized void waitForAdd() throws InterruptedException {
		if (pauseAdd)
			wait();
	}

	synchronized void waitForMinus() throws InterruptedException {
		if (!pauseAdd)
			wait();
	}
}

class Cls1 implements Runnable {
	private Data data;

	Cls1(Data data) {
		this.data = data;
	}

	public void run() {
		while (!Thread.interrupted()) {
			try {
				data.waitForAdd();
				data.add();
				TimeUnit.MICROSECONDS.sleep(1000);
				Thread.yield();
			} catch (Exception e) {
				System.out.println("Exiting from addition task...");
				return;
			}
		}
	}
}

class Cls2 implements Runnable {
	private Data data;

	Cls2(Data data) {
		this.data = data;
	}

	public void run() {
		while (!Thread.interrupted()) {
			try {
				data.waitForMinus();
				data.subtract();
				TimeUnit.MICROSECONDS.sleep(1000);
				Thread.yield();
			} catch (InterruptedException e) {
				System.out.println("Exiting from subtraction task...");
				return;
			}
		}
	}
}

class Test {
	public static void main(String args[]) throws InterruptedException {
		Data data = new Data();
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < 2; i++) {
			exec.execute(new Cls1(data));
			exec.execute(new Cls2(data));
		}
		TimeUnit.SECONDS.sleep(3); // run 3 seconds
		exec.shutdownNow();
	}
}

相关推荐

Global site tag (gtag.js) - Google Analytics