編寫代碼,使用3個線程,1個線程打印X,一個線程打印Y,一個線程打印Z,同時執行連續打印10次"XYZ"。
本題解題采用volatile實現,主要考察的點是volatile內存可見性問題。
public class Test { private static volatile Integer Count = 0; private static volatile Integer a = 0; public static void main(String[] args) { Thread one = new Thread(new Runnable() { @Override public void run() { while (true) { if (a == 0) { System.out.print("X"); a = 1; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread two = new Thread(new Runnable() { @Override public void run() { while (true) { if (a == 1) { System.out.print("Y"); a = 2; } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread three = new Thread(new Runnable() { @Override public void run() { while (true) { if (a == 2) { System.out.println("Z"); a = 0; Count++; if(Count == 10) { System.exit(0); } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }); one.start(); two.start(); three.start(); } }