如何控制超时的线程?

多线程 java xue8 8天前 14次浏览



使用CountDownLatch控制多个线程之间的同步。


我想问
如果某一个线程发生了死循环,那么我该如何手动把他kill掉?
或者说当某个线程发生死循环时,如何及时知道并结束本次请求,避免浪费服务器资源。


不能使用这种形式: future.get(3,TimeUnit.SECONDS);

public class TestCountDownLatch {
public static void main(String[] args) {
final CountDownLatch countDownLatch = new CountDownLatch(2);
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Runnable() {
public void run() {
Boolean b = true;
//模拟这里发生了死循环
while (b){
}
// countDownLatch.countDown();
}
});

ExecutorService pool2 = Executors.newSingleThreadExecutor();
pool2.execute(new Runnable() {
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
countDownLatch.countDown();
}
});

try {
countDownLatch.await(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("结束===================");
}
}




回答:
[]

0条回复
撰写答案