java 线程超时 中断线程

2018-05-09  本文已影响0人  乘以零

设定一个线程最多运行3秒 超过3秒就中断 两种方法

1.用Future

final ExecutorService exec = Executors.newFixedThreadPool(1);
Future<Object> future = exec.submit(() -> {
    for (int i = 1; i <= 1000; i++) {
        System.out.println(i + "");
        Thread.sleep(1000L);
    }
    return null;
});
try {
    future.get(3000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
    e.printStackTrace();
    future.cancel(true);//必须代码
}
System.out.println("end");

2.Thread.interrupt (严格来说没啥用 因为正常的逻辑代码中不会有Thread.sleep())

Thread t1 = new Thread(() -> {
    for (int i = 1; i <= 1000; i++) {
        System.out.println(i + "");
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new RuntimeException(e); //必须抛出异常 不然还是会继续执行
        }
    }
});
t1.start();
try {
    t1.join(3000);
} catch (InterruptedException e) {
    e.printStackTrace();
}
t1.interrupt(); //核心代码
System.out.println("end");
上一篇 下一篇

猜你喜欢

热点阅读