package t1t2t3t4; /** * Created by Administrator on 2017/5/13. */ public class Main { public static void main(String[] args) { Object lock = new Object(); for(int i=1;i<=4;i++){ char str=(char) (64+i); System.out.print(str+":"); NumberThread n = new NumberThread(); n.state=i; Thread t1 = new Thread(n); t1.setName("線程1"); Thread t2 = new Thread(n); t2.setName("線程2"); Thread t3 = new Thread(n); t3.setName("線程3"); Thread t4 = new Thread(n); t4.setName("線程4"); t1.start();t2.start();t3.start();t4.start(); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); } } }
package t1t2t3t4; /** * Created by Administrator on 2017/5/13. */ public class NumberThread implements Runnable { int count = 0; int state = 1; //記錄當前要執行的線程 public void run() { while (true) { //傳對象,通過鎖這個對象,判斷資源的鎖定狀態 synchronized (this) { //如果線程名中包含state,表示線程名正確,打印數字 if (Thread.currentThread().getName().contains(state + "")) { System.out.print(state); //正確線程打印一次後,增加state,用於下次正確的線程打印 count++; state++; }else{ //要運行的線程和state不一致,則休眠, 等待下次喚醒 try { wait(); } catch (InterruptedException e) { } } //state加到4,從1開始 if (state == 5) { state = 1; //通知其他所有線程運行。不知道運行的是哪個線程 } //喚醒所有線程 notifyAll(); if (count == 12) { break; } } } } }
運行結果:
A:123412341234
B:234123412341
C:341234123412
D:412341234123