public class Solution2 { private static final Object lock = new Object(); //表示對象鎖 private volatile int index = 1; //表示要輸出的數字 private volatile boolean aHasPrint = false; //記錄A是否被打印過 class A implements Runnable { @Override public void run() { for (int i = 0; i < 50; i++) { synchronized (lock) { while (aHasPrint) { //如果A已經打印過就進行阻塞 try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("A:" + index); //A沒有打印過則輸出A的值 index++; //輸出的值增加1 aHasPrint = true; //表示A已經打印過 lock.notifyAll(); //喚醒其它線程執行 } } } } class B implements Runnable { @Override public void run() { for (int i = 0; i < 50; i++) { synchronized (lock) { while (!aHasPrint) { //如果A沒有打印過則阻塞 try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("B:" + index); //輸出B的值 index++; //計數加一 aHasPrint = false; //B打印完了說明新的一輪開始了,將標識為計為A沒有打印過 lock.notifyAll(); //喚醒阻塞線程 } } } } public static void main(String[] args) { Solution2 solution2 = new Solution2(); Thread threadA = new Thread(solution2.new A()); Thread threadB = new Thread(solution2.new B()); threadA.start(); threadB.start(); } }
相關代碼 https://github.com/LiWangCai/blogRelated 可自行獲取