import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class Task implements Runnable{
private CyclicBarrier cyclicBarrier;
public Task(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "準備就緒");
cyclicBarrier.await();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + "中斷了......");
} catch (BrokenBarrierException e) {
System.out.println(Thread.currentThread().getName() + "拋出損壞異常....");
}
}
}
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("主線程開始......");
CyclicBarrier cb = new CyclicBarrier(3, new Runnable(){
@Override
public void run() {
System.out.println("子線程全部就位,開始執(zhí)行制定任務......");
}
});
Thread t1 = new Thread(new Task(cb), "Thread-1");
Thread t2 = new Thread(new Task(cb), "Thread-2");
Thread t3 = new Thread(new Task(cb), "Thread-3");
t1.start();
t2.start();
t3.start();
Thread.sleep(2000);
System.out.println("主線程執(zhí)行完畢");
}
}
成都創(chuàng)新互聯(lián)主營玉溪網站建設的網絡公司,主營網站建設方案,重慶APP開發(fā)公司,玉溪h5微信平臺小程序開發(fā)搭建,玉溪網站營銷推廣歡迎玉溪等地區(qū)企業(yè)咨詢
import java.util.concurrent.CyclicBarrier;
public class Main {
public static void main(String[] args) throws InterruptedException {
System.out.println("主線程開始......");
CyclicBarrier cb = new CyclicBarrier(4, new Runnable(){
@Override
public void run() {
System.out.println("子線程全部就位,開始執(zhí)行制定任務......");
}
});
Thread t1 = new Thread(new Task(cb), "Thread-1");
Thread t2 = new Thread(new Task(cb), "Thread-2");
Thread t3 = new Thread(new Task(cb), "Thread-3");
t1.start();
t2.start();
t3.start();
Thread.sleep(1000);
t1.interrupt();
Thread.sleep(2000);
System.out.println("主線程執(zhí)行完畢");
}
}
網頁題目:多線程(八、同步計數(shù)器-CyclicBarrier)
分享路徑:http://jinyejixie.com/article28/ghhgcp.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供品牌網站設計、App設計、商城網站、網站設計、域名注冊、網站內鏈
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)