我知道Thread.stop()和其他函数已被弃用,如果满足特定条件,我想停止线程的运行。这是我现在正在做的简化版本:
public class SomeThread extends Thread
{
private static boolean running = true;
public static void shutdown()
{
running = false;
}
public void run()
{
while( running )
{
// do something cool
}
return; // <- this is what I'm wondering about
}
}
当另一个类调用SomeThread的shutdown()方法时,while循环退出,然后run()方法返回。这样安全吗?
我使用while循环而不是只让run()进行工作的主要原因是因为有些事情我只想做一次(在while循环之前),而我实际上只在使用线程并发。我确定这是Threads的含义的 SCSS ,但我主要是想知道return语句。
最佳答案
返回结果很好,其余的代码也很不稳定。running
成员应该是 volatile 的,或者您需要对该变量的读写进行一些同步。
(将shutdown
和running
设为静态是不寻常的。)