做bc网站排名/网络营销环境分析
这是一个简单的解决方案,但我不知道它是否最有效:只需声明一个带有公共布尔字段的对象.
public class TerminationEvent {
public boolean terminated = false;
}
在启动线程之前,创建一个新的TerminationEvent对象.在构造线程对象时使用此对象作为参数,例如
public class MyThread implements Runnable {
private TerminationEvent terminationEvent;
public MyThread(TerminationEvent event) {
terminationEvent = event;
}
}
同一个对象将被传递给每个MyThread,因此它们都将看到相同的布尔值.
现在,每个MyThread中的run()方法都会有类似的东西
if (terminationEvent.terminated) {
break;
}
在循环中,将设置terminationEvent.terminated = true;当其他线程需要停止时.
(通常我不会使用像终止这样的公共字段,但是你说你想要效率.我认为这比getter方法更有效,但我还没有尝试过基准测试任何东西.另外,在这样的简单情况下,当线程读取或写入终止字段时,我认为您不必担心同步.)