您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。