2013-04-05 105 views
5

我一直在寻找方法来杀死一个线程,看来这是最流行的方法替代方法杀死线程

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(); 
    } 
} 

但是,如果在while循环中,我们产生另一个而它与填充另一个对象数据(比如正在运行和更新的gui),那么我们如何回调 - 特别是考虑到这种方法可能会被多次调用,所以我们有很多线程,而while(running)然后改变标志为一个会改变它为每个人?

谢谢

+4

**没有一个解决方案,但最佳实践:**声明你的标志'running'为'volatile'。 – 2013-04-05 14:48:45

+0

线程查杀的最佳方法是不要尝试。如果有任何方法可以设计应用程序,以便线程无需在操作系统在进程终止时杀死线程时被杀死,那么您应该这样做。 – 2013-04-05 14:56:53

+0

但如果run方法有无限循环,即使关闭了gui线程正在将数据抽入,它仍然不会死亡:( – Biscuit128 2013-04-05 14:57:59

回答

2

解决这些问题的一种方法是拥有一个Monitor类来处理所有的线程。它可以启动所有必要的线程(可能在不同的时间/必要时),一旦你想关闭,你可以调用一个关闭方法来中断所有(或某些)线程。

另外,实际上调用Thread s interrupt()方法通常是一个更好的方法,因为它会摆脱阻塞动作,抛出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(); 
    } 
} 
+2

你的意思是'while(!isInterrupted()) '? – z5h 2013-04-05 15:11:29

+0

当然,谢谢! – ddmps 2013-04-05 21:13:08

+1

这是一本名为'Java Concurrency in Practice'的书中推荐的方法,由JDK并发设计师(Tim Peierls Joshua Bloch Joseph Bowbeer David Holmes和Doug Lea)共同撰写。 .stop'绝对是depreca特德。 – 2013-04-06 05:41:17

0

我添加了一个utlility类本质上有一个静态地图和方法

该地图的类型是Long id, Thread thread。我添加了两个方法一个添加到地图和一个停止线程通过使用中断此方法采用id作为参数。

我也改变了我的循环逻辑while真的,同时! isInterrupted。这是方法确定,或者这是一种不好的编程风格/公约

感谢