CountDownLatch控制线程是否超时

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);
    }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容