1.thread的两种阻塞方法
thread.join(2000);//等待2s
CountDownLatch countDownLatch = new CountDownLatch(10);
countDownLatch.countDown();//递减
countDownLatch .await();//等待countDownLatch数量为0
2.样例代码
import java.util.concurrent.CountDownLatch;
/**
* 测试线程阻塞
* @Author dabai
* @Date 2019/6/21
*/
public class TestThreadBlock {
static CountDownLatch countDownLatch = new CountDownLatch(10);
public static void main(String[] args) throws InterruptedException {
System.out.println("主线程开始");
Thread t1 = new MyThread();
t1.start();
//线程阻塞 等待线程完成 再执行下一步
// t1.join(2000);
countDownLatch.await();
System.out.println("主线程结束");
}
static class MyThread extends Thread{
@Override
public void run() {
for (int i =0 ;i<10;i++){
System.out.println(Thread.currentThread().getName()+"正在执行"+i);
countDownLatch.countDown();
}
}
}
}
网友评论