給出一個題目,有3個線程,我但願線程1向控制檯輸出3行信息後,線程2向控制檯輸出6行信息,接下來是線程3輸出10行信息到控制檯,如此循環10次。在一個線程輸出信息的時候,其餘線程不能產生干擾。java
package com.concurrent.condition; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /*================================== * 描述:有3個線程,線程1連續輸出3次,而後讓線程2連續輸出6次,接下來線程3連續輸出10次。依次循環10次 * 做者:零下三度 ==================================*/ public class ConditionExample { public static void main(String[] args) { final Outer outer = new Outer(); final int loopNum = 10; // 線程1 new Thread(new Runnable() { @Override public void run() { for (int i = 1; i < loopNum; i++) { outer.out1(i); } } }).start(); // 線程2 new Thread(new Runnable() { @Override public void run() { for (int i = 1; i < loopNum; i++) { outer.out2(i); } } }).start(); // 線程3 new Thread(new Runnable() { @Override public void run() { for (int i = 1; i < loopNum; i++) { outer.out3(i); } } }).start(); } } class Outer { Lock lock = new ReentrantLock(); Condition condition1 = lock.newCondition(); Condition condition2 = lock.newCondition(); Condition condition3 = lock.newCondition(); int currentNo = 1; // 線程1的輸出方法 public void out1(int loopNum) { try { lock.lock(); while (currentNo != 1) { try { condition1.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < 3; i++) { System.out.println("this Thread1 outer no." + i + " ; loop=" + loopNum); } currentNo = 2;//標誌態置換爲線程2能夠輸出的標誌 condition2.signal();// 通知線程2開始了 } finally { lock.unlock(); } } //線程2的輸出方法 public void out2(int loopNum) { try { lock.lock(); while (currentNo != 2) { try { condition2.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < 6; i++) { System.out.println("this Thread2 outer no." + i + " ; loop=" + loopNum); } currentNo = 3;//標誌態置換爲線程3能夠輸出的標誌 condition3.signal();//通知線程3 } finally { lock.unlock(); } } //線程3的輸出方法 public void out3(int loopNum) { try { lock.lock(); while (currentNo != 3) { try { condition3.await(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 0; i < 10; i++) { System.out.println("this Thread3 outer no." + i + " ; loop=" + loopNum); } currentNo = 1;//標誌態置換爲線程2能夠輸出的標誌 condition1.signal();//通知線程1 } finally { lock.unlock(); } } }