美文网首页
Thread的两种阻塞方法

Thread的两种阻塞方法

作者: 大白乐了 | 来源:发表于2019-06-21 09:56 被阅读0次

    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();
                }
            }
        }
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:Thread的两种阻塞方法

          本文链接:https://www.haomeiwen.com/subject/jbveqctx.html