美文网首页
CountDownLatch控制线程是否超时

CountDownLatch控制线程是否超时

作者: 冷枫abc | 来源:发表于2020-12-02 17:45 被阅读0次
    public static void main(String[] args) throws InterruptedException {
            CountDownLatch latch = new CountDownLatch(1);
            long start = System.currentTimeMillis();
            System.out.println("I'am start--->" + start);
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("I'am dead");
                        Thread.sleep(50000000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
    
                    }
                    latch.countDown();
                }
            });
            t.start();
    
            latch.await(10, TimeUnit.SECONDS);  //等待10秒后,如果线程没有执行完,则不再等待,进入后续
            System.out.println("Game Over");
            t.interrupt();
           // t.stop();
            long end = System.currentTimeMillis();
            System.out.println("I'am end--->" + end);
            System.out.println(end - start);
        }
    

    相关文章

      网友评论

          本文标题:CountDownLatch控制线程是否超时

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