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() + "準(zhǔn)備就緒");
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í)行制定任務(wù)......");
}
});
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)主營玉溪網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP開發(fā)公司,玉溪h5微信平臺小程序開發(fā)搭建,玉溪網(wǎng)站營銷推廣歡迎玉溪等地區(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í)行制定任務(wù)......");
}
});
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í)行完畢");
}
}
網(wǎng)頁題目:多線程(八、同步計數(shù)器-CyclicBarrier)
分享路徑:http://muchs.cn/article28/ghhgcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計、App設(shè)計、商城網(wǎng)站、網(wǎng)站設(shè)計、域名注冊、網(wǎng)站內(nèi)鏈
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)