java 線程 新類庫中的構件 CyclicBarrier使用,類庫cyclicbarrier

來源:互聯網
上載者:User

java 線程 新類庫中的構件 CyclicBarrier使用,類庫cyclicbarrier

package org.rui.thread.newc;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/** * 賽馬遊戲 CyclicBarrier *  * @author lenovo *  */class Horse implements Runnable {private static int counter = 0;private final int id = counter++;private int strides = 0;private static Random rand = new Random(47);private static CyclicBarrier barrier;public Horse(CyclicBarrier b) {barrier = b;}public synchronized int getStrides() {return strides;}@Overridepublic void run() {try {while (!Thread.interrupted()) {synchronized (this) {//每場比賽都會加上隨機 跨過的數字 0,1 or 2strides += rand.nextInt(3);// produces 0,1 or 2}// 等待所有的馬都準備完畢,當所有的馬向前移動時,cyclicBarrier將自動調用runnable柵欄動作任務,按順序顯示馬和終點的位置barrier.await();}} catch (InterruptedException e) {} catch (BrokenBarrierException e) {throw new RuntimeException(e);}}public String toString() {return "Horse" + id + " ";}// 軌道public String tracks() {StringBuilder s = new StringBuilder();for (int i = 0; i < getStrides(); i++) {s.append("*");}s.append(id);return s.toString();}}public class HorseRace {static final int FINISH_LINE = 75;// 結束 行private List<Horse> horses = new ArrayList<Horse>();private ExecutorService exec = Executors.newCachedThreadPool();private CyclicBarrier barrier;public HorseRace(int nHorses, final int pause) {barrier = new CyclicBarrier(nHorses/*等待的數量*/, new Runnable() {@Overridepublic void run() {//列印資訊 StringBuilder sb = new StringBuilder();for (int i = 0; i < FINISH_LINE; i++) {sb.append("=");// 賽馬場上的柵欄}System.out.println(sb);for (Horse horse : horses) {System.out.println(horse.tracks());}for (Horse horse : horses) {//System.out.println("strides:@@@@@@@" + horse.getStrides());if (horse.getStrides() >= FINISH_LINE) {//System.out.println(horse + "贏得!");exec.shutdownNow();return;}}try {TimeUnit.MILLISECONDS.sleep(pause);} catch (InterruptedException e) {System.out.println("barrier-action sleep interrupted");}}});// 一旦所有的馬都越過了柵欄,它就會自動地為下一回合比賽做好準備for (int i = 0; i < nHorses; i++) {Horse horse = new Horse(barrier);//每個馬都分配一個barrierhorses.add(horse);exec.execute(horse);}}/** * main *  * @param args */public static void main(String[] args) {int nHorses = 7; //指定馬的數量int pause = 200;//停頓時間String[] arg = {};if (arg.length > 0) {// optional argumentint n = new Integer(arg[0]);nHorses = n > 0 ? n : nHorses;}if (arg.length > 1) {// optional argumentint p = new Integer(arg[1]);pause = p > -1 ? p : pause;}// 競賽new HorseRace(nHorses, pause);}}/** ===========================================================================**0**1*2**3*4**5*6===========================================================================**0***1*2**3*4***5***6===========================================================================***0****1***2***3**4*****5****6===========================================================================*****0****1*****2****3**4******5****6===========================================================================******0****1******2*****3****4******5*****6===========================================================================******0******1******2******3****4*******5*****6===========================================================================*******0******1*******2******3*****4********5*******6===========================================================================********0******1********2*******3*******4*********5*********6===========================================================================********0******1*********2*******3*********4*********5*********6===========================================================================**********0*******1**********2********3*********4***********5*********6===========================================================================**********0*******1************2*********3*********4*************5*********6===========================================================================************0*******1*************2***********3**********4***************5***********6===========================================================================************0********1*************2*************3***********4***************5*************6===========================================================================**************0********1*************2*************3*************4......
...此處省略列印線===========================================================================**********************************************************************0*******************************************************1******************************************************************2***********************************************************************3***********************************************************************4***********************************************************************5*************************************************************6===========================================================================***********************************************************************0*******************************************************1*******************************************************************2*************************************************************************3***********************************************************************4*************************************************************************5***************************************************************6===========================================================================************************************************************************0********************************************************1*******************************************************************2***************************************************************************3***********************************************************************4***************************************************************************5****************************************************************6Horse3 贏得! */

一個容易理解的張孝祥老師講解例子 

package test;import java.util.concurrent.BrokenBarrierException;import java.util.concurrent.CyclicBarrier;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * CyclicBarrier 應用 * @author lenovo * */public class CyclicBarrierTest {public static void main(String[] args) {ExecutorService service = Executors.newCachedThreadPool();final CyclicBarrier cb = new CyclicBarrier(3); // 三個線程同時到達for (int i = 0; i < 3; i++) {Runnable runnable = new Runnable() {public void run() {try {Thread.sleep((long) (Math.random() * 10000));System.out.println("線程"+ Thread.currentThread().getName()+ "即將到達集合地點1,當前已有"+ (cb.getNumberWaiting() + 1)+ "個已到達"+ (cb.getNumberWaiting() == 2 ? "都到齊了,繼續走啊": "正在等候"));try {cb.await();} catch (BrokenBarrierException e) {e.printStackTrace();}Thread.sleep((long) (Math.random() * 10000));System.out.println("線程"+ Thread.currentThread().getName()+ "即將到達集合地點2,當前已有"+ (cb.getNumberWaiting() + 1)+ "個已到達"+ (cb.getNumberWaiting() == 2 ? "都到齊了,繼續走啊": "正在等候"));try {cb.await();} catch (BrokenBarrierException e) {e.printStackTrace();}Thread.sleep((long) (Math.random() * 10000));System.out.println("線程"+ Thread.currentThread().getName()+ "即將到達集合地點3,當前已有"+ (cb.getNumberWaiting() + 1)+ "個已到達"+ (cb.getNumberWaiting() == 2 ? "都到齊了,繼續走啊": "正在等候"));try {cb.await();} catch (BrokenBarrierException e) {e.printStackTrace();}} catch (InterruptedException e) {e.printStackTrace();}}};service.execute(runnable);}service.shutdown();}}/** * output:線程pool-1-thread-3即將到達集合地點1,當前已有1個已到達正在等候線程pool-1-thread-1即將到達集合地點1,當前已有2個已到達正在等候線程pool-1-thread-2即將到達集合地點1,當前已有3個已到達都到齊了,繼續走啊線程pool-1-thread-2即將到達集合地點2,當前已有1個已到達正在等候線程pool-1-thread-1即將到達集合地點2,當前已有2個已到達正在等候線程pool-1-thread-3即將到達集合地點2,當前已有3個已到達都到齊了,繼續走啊線程pool-1-thread-3即將到達集合地點3,當前已有1個已到達正在等候線程pool-1-thread-2即將到達集合地點3,當前已有2個已到達正在等候線程pool-1-thread-1即將到達集合地點3,當前已有3個已到達都到齊了,繼續走啊 */





幫我看看以下的JAVA程式(線程相關)

countDown知道嗎?下面這樣:

public static void main(String[] args) throws InterruptedException {
int threadNumber = 10;
final CountDownLatch countDownLatch = new CountDownLatch(threadNumber);
for (int i = 0; i < threadNumber; i++) {
final int threadID = i;
new Thread() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(String.format("threadID:[%s] finished!!", threadID));
countDownLatch.countDown();
}
}.start();
}

countDownLatch.await();
System.out.println("main thread finished!!");
}
 
Java 多線程式控制制

1.用等待,第一個線程執行完畢後,再讓第2個線程運行,第2個結束後,再運行第3個。有個方法Join可以利用。
2.可以
3.不能,隊列只是一種資料結構,控制線程只能用線程相關的方法。
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.