您好,登錄后才能下訂單哦!
package com.jane;
import java.util.concurrent.CountDownLatch;
public class Task implements Runnable {
private CountDownLatch countDownLatch;
private String name;
public Task(CountDownLatch countDownLatch, String name) {
this.countDownLatch = countDownLatch;
this.name = name;
}
@Override
public void run() {
try {
System.out.println(name + "開始等待開關......");
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + "執行任務完成");
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
//主線程創建,和子線程共享
CountDownLatch countDownLatch = new CountDownLatch(1);
System.out.println("主線程啟動......");
//創建3個子線程
Thread t1 = new Thread(new Task(countDownLatch, "線程-1"));
Thread t2 = new Thread(new Task(countDownLatch, "線程-2"));
Thread t3 = new Thread(new Task(countDownLatch, "線程-3"));
t1.start();
t2.start();
t3.start();
Thread.sleep(2000);
System.out.println("主線程執行任務完畢,放行......");
countDownLatch.countDown();
System.out.println("主線程執行完畢");
}
}
package com.jane;
import java.util.concurrent.CountDownLatch;
public class Task1 implements Runnable {
private CountDownLatch countDownLatch;
private String name;
public Task1(CountDownLatch countDownLatch, String name) {
this.countDownLatch = countDownLatch;
this.name = name;
}
@Override
public void run() {
try {
System.out.println(name + "開始開始執行任務......");
Thread.sleep(2000);
System.out.println(name + "執行任務完成");
countDownLatch.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.jane;
import java.util.concurrent.CountDownLatch;
public class Main1 {
public static void main(String[] args) throws InterruptedException {
//主線程創建,和子線程共享
CountDownLatch countDownLatch = new CountDownLatch(3);
System.out.println("主線程啟動......");
//創建3個子線程
Thread t1 = new Thread(new Task1(countDownLatch, "線程-1"));
Thread t2 = new Thread(new Task1(countDownLatch, "線程-2"));
Thread t3 = new Thread(new Task1(countDownLatch, "線程-3"));
t1.start();
t2.start();
t3.start();
System.out.println("主線程等待子線程執行結果......");
countDownLatch.await();
System.out.println("主線程執行完畢");
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。