有三个线程ID分别是A、B、C,用多线程编程实现,在屏幕上循环打印10次ABCABC…

迅雷的一道面试题:

题目:有三个线程ID分别是A、B、C,请用多线程编程实现,在屏幕上循环打印10次ABCABC…

 

public class TestThread {
	/**
	 * @author lucky
	 */

	public static void main(String[] args) {
		new Thread(new TestRun("A")).start();
		new Thread(new TestRun("B")).start();
		new Thread(new TestRun("C")).start();
	}

}

class TestRun implements Runnable {
	private String name;
	private static String flag = "A";
	private int count = 10;

	TestRun(String name) {
		this.name = name;
	}

	@Override
	public void run() {
		while (count > 0) {                             
			synchronized (flag) {  
				if (flag.equals(name)) {
					System.out.print(name);
					count--;
					if (name.equals("A"))
						flag = "B";
					if (name.equals("B"))
						flag = "C";
					if (name.equals("C"))
						flag = "A";
				}
			}
		}
	}

}

PS:其实这里可以不用synchronized (flag)也能输出正确结果,但会造成线程空转,就不大好了

上一篇:经典n皇后问题java代码实现


下一篇:使用dbms_stats但不生成histogram的方法