Bis*_*128 5 java concurrency multithreading
我一直在寻找杀死线程的方法,看起来这是最流行的方法
public class UsingFlagToShutdownThread extends Thread {
private boolean running = true;
public void run() {
while (running) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {}
}
System.out.println("Shutting down thread");
}
public void shutdown() {
running = false;
}
public static void main(String[] args)
throws InterruptedException {
UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
t.start();
Thread.sleep(5000);
t.shutdown();
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果在while循环中我们生成了另一个被数据填充的对象(比如运行和更新的gui),那么我们如何回调 - 特别是考虑到这个方法可能已被多次调用,所以我们有很多线程而(运行)然后更改一个标志将改变它为每个人?
谢谢
解决这些问题的一种方法是使用一个处理所有线程的 Monitor 类。它可以启动所有必要的线程(可能在不同时间/必要时),一旦您想要关闭,您可以调用关闭方法来中断所有(或部分)线程。
另外,实际上调用Threadsinterrupt()方法通常是一种更好的方法,因为这样它将摆脱抛出的阻塞操作InterruptedException(例如等待/睡眠)。然后它将设置一个线程中已经存在的标志(可以使用 检查isInterrupted()或检查和清除interrupted()。例如,以下代码可以替换您当前的代码:
public class UsingFlagToShutdownThread extends Thread {
public void run() {
while (!isInterrupted()) {
System.out.print(".");
System.out.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) { interrupt(); }
}
System.out.println("Shutting down thread");
}
public static void main(String[] args)
throws InterruptedException {
UsingFlagToShutdownThread t = new UsingFlagToShutdownThread();
t.start();
Thread.sleep(5000);
t.interrupt();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
256 次 |
| 最近记录: |