Java,三條執行緒依次交替輸出十次ABC
阿新 • • 發佈:2019-01-25
public class MyThreadTest { public static void main(String[] args) { PrintABC printABC = new PrintABC(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { printABC.printA(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { printABC.printB(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; i++) { printABC.printC(); } } }).start(); }//main } class PrintABC { private int flag = 1; public synchronized void printA() { while (flag != 1) { try { this.wait();// this表示當前方法所在的物件 } catch (InterruptedException e) { e.printStackTrace(); } } flag = 2; System.out.println("A"+ "," + Thread.currentThread().getName()); this.notifyAll(); } public synchronized void printB() { while (flag != 2) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } flag = 3; System.out.println("B"+ "," + Thread.currentThread().getName()); this.notifyAll(); } public synchronized void printC() { while (flag != 3) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } flag = 1; System.out.println("C"+ "," + Thread.currentThread().getName()); this.notifyAll(); } }
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2
A,Thread-0
B,Thread-1
C,Thread-2