啓動3個線程打印遞增的數字, 線程1先打印1,2,3,4,5, 而後是線程2打印6,7,8,9,10, 而後是線程3打印11,12,13,14,15. 接着再由線程1打印16,17,18,19,20....以此類推, 直到打印到75. 程序的輸出結果應該爲:java
線程1: 1
線程1: 2
線程1: 3
線程1: 4
線程1: 5網絡
線程2: 6
線程2: 7
線程2: 8
線程2: 9
線程2: 10
...
線程3: 71
線程3: 72
線程3: 73
線程3: 74
線程3: 75ide
import java.util.ArrayList; import java.util.List; /** * Created by ibm on 2017/8/8. */ public class ClassicTest { //使用原始的synchornized object.wait() object.notify() public static void main(String[] args) { //定義線程組 List<MyThread> threadGroups = new ArrayList<>(); Counter counter = new Counter(); MyThread t1 = new MyThread(1,"一",counter,threadGroups); MyThread t2 = new MyThread(2,"二",counter,threadGroups); MyThread t3 = new MyThread(2,"三",counter,threadGroups); threadGroups.add(t1); threadGroups.add(t2); threadGroups.add(t3); new Thread(t1).start(); new Thread(t2).start(); new Thread(t3).start(); } } class MyThread implements Runnable{ //線程運行狀態 1立刻執行,2阻塞 public int status; //線程名字 public String name; //計數器 public Counter counter; //線程組 public List<MyThread> threads = new ArrayList<>(); public MyThread(int status,String name,Counter counter,List<MyThread> threads){ this.status = status; this.name = name; this.counter = counter; this.threads = threads; } @Override public void run() { System.out.println(name + " GET " + status); synchronized (counter){ while (!counter.isEnd()){ //判斷是否該本身執行,切記使用while,由於若是在循環的等待過程當中status有所變化,這裏須要再次判斷 while (status != 1){ try { counter.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for(int i = 0;i < 5 ;i ++){ System.out.println(name + ":" + counter.get()); counter.increase(); } //狀態進入阻塞狀態,並設置下一個能夠運行的線程 status = 2; setNext(); counter.notifyAll(); System.out.println("----"); } } } void setNext(){ //當前線程在線程組的索引 int index = 0; for(index = 0;index < threads.size();index++){ if(name.equals(threads.get(index).name)){ break; } } if(index == (threads.size() - 1)){ threads.get(0).status = 1; }else { threads.get(index + 1).status = 1; } } } class Counter{ int num = 1; int end = 75; public int get(){ return num; } public void increase(){ if(isEnd()){ System.out.println("num超過限制"); return; } num++; } public boolean isEnd(){ if(num >= end){ return true; } return false; } }
1.使用synchronized關鍵字:this
public class ClassicTest1 { // n爲即將打印的數字 private static int n = 1; // state=1表示將由線程1打印數字, state=2表示將由線程2打印數字, state=3表示將由線程3打印數字 private static int state = 1; public static void main(String[] args) { final ClassicTest1 pn = new ClassicTest1(); new Thread(new Runnable() { public void run() { // 3個線程打印75個數字, 單個線程每次打印5個連續數字, 所以每一個線程只需執行5次打印任務. 3*5*5=75 for (int i = 0; i < 5; i++) { // 3個線程都使用pn對象作鎖, 以保證每一個交替期間只有一個線程在打印 synchronized (pn) { // 若是state!=1, 說明此時還沒有輪到線程1打印, 線程1將調用pn的wait()方法, 直到下次被喚醒 while (state != 1) try { pn.wait(); } catch (InterruptedException e) { e.printStackTrace(); } // 當state=1時, 輪到線程1打印5次數字 for (int j = 0; j < 5; j++) { // 打印一次後n自增 System.out.println(Thread.currentThread().getName() + ": " + n++); } System.out.println(); // 線程1打印完成後, 將state賦值爲2, 表示接下來將輪到線程2打印 state = 2; // notifyAll()方法喚醒在pn上wait的線程2和線程3, 同時線程1將退出同步代碼塊, 釋放pn鎖. // 所以3個線程將再次競爭pn鎖 // 假如線程1或線程3競爭到資源, 因爲state不爲1或3, 線程1或線程3將很快再次wait, 釋放出剛到手的pn鎖. // 只有線程2能夠經過state斷定, 因此線程2必定是執行下次打印任務的線程. // 對於線程2來講, 得到鎖的道路也許是曲折的, 但前途必定是光明的. pn.notifyAll(); } } } }, "線程1").start(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { synchronized (pn) { while (state != 2) try { pn.wait(); } catch (InterruptedException e) { e.printStackTrace(); } for (int j = 0; j < 5; j++) { System.out.println(Thread.currentThread().getName() + ": " + n++); } System.out.println(); state = 3; pn.notifyAll(); } } } }, "線程2").start(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { synchronized (pn) { while (state != 3) try { pn.wait(); } catch (InterruptedException e) { e.printStackTrace(); } for (int j = 0; j < 5; j++) { System.out.println(Thread.currentThread().getName() + ": " + n++); } System.out.println(); state = 1; pn.notifyAll(); } } } }, "線程3").start(); } }
2.使用condition與lock線程
public class ClassicTest2 implements Runnable { private int state = 1; private int n = 1; // 使用lock作鎖 private ReentrantLock lock = new ReentrantLock(); // 得到lock鎖的3個分支條件 private Condition c1 = lock.newCondition(); private Condition c2 = lock.newCondition(); private Condition c3 = lock.newCondition(); @Override public void run() { new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { try { // 線程1得到lock鎖後, 其餘線程將沒法進入須要lock鎖的代碼塊. // 在lock.lock()和lock.unlock()之間的代碼至關於使用了synchronized(lock){} lock.lock(); while (state != 1) try { // 線程1競爭到了lock, 可是發現state不爲1, 說明此時還未輪到線程1打印. // 所以線程1將在c1上wait // 與解法一不一樣的是, 三個線程並不是在同一個對象上wait, 也不禁同一個對象喚醒 c1.await(); } catch (InterruptedException e) { e.printStackTrace(); } // 若是線程1競爭到了lock, 也經過了state斷定, 將執行打印任務 for (int j = 0; j < 5; j++) { System.out.println(Thread.currentThread().getName() + ": " + n++); } System.out.println(); // 打印完成後將state賦值爲2, 表示下一次的打印任務將由線程2執行 state = 2; // 喚醒在c2分支上wait的線程2 c2.signal(); } finally { // 打印任務執行完成後須要確保鎖被釋放, 所以將釋放鎖的代碼放在finally中 lock.unlock(); } } } }, "線程1").start(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { try { lock.lock(); while (state != 2) try { c2.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int j = 0; j < 5; j++) { System.out.println(Thread.currentThread().getName() + ": " + n++); } System.out.println(); state = 3; c3.signal(); } finally { lock.unlock(); } } } }, "線程2").start(); new Thread(new Runnable() { public void run() { for (int i = 0; i < 5; i++) { try { lock.lock(); while (state != 3) try { c3.await(); } catch (InterruptedException e) { e.printStackTrace(); } for (int j = 0; j < 5; j++) { System.out.println(Thread.currentThread().getName() + ": " + n++); } System.out.println(); state = 1; c1.signal(); } finally { lock.unlock(); } } } }, "線程3").start(); } public static void main(String[] args) { new ClassicTest2().run(); } }