这是我在编写只需要一个线程并且需要执行特定任务的类时使用的简单线程模式。
这种类通常需要具备可启动、可停止和可重启动的功能。您是否看到我使用的这种模式存在任何问题?
public class MyThread implements Runnable {
private boolean _exit = false;
private Thread _thread = null;
public void start () {
_exit = false;
if (_thread == null) {
_thread = new Thread(this, "MyThread");
_thread.start();
}
}
public void run () {
while (!_exit) {
//do something
}
}
public void stop () {
_exit = true;
if (_thread != null) {
_thread.interrupt();
_thread = null;
}
}
}
我正在寻求关于是否有遗漏的意见,或者是否有更好的编写方法。
start(); stop();
,那么对start();
的进一步调用将启动一个立即退出的线程。我认为这并没有增加使用Thread
直接的优势(正如其中一个答案所建议的那样,转向线程池和执行器服务是个好主意,尽管这使得简单的示例需要更多地了解 Java 库)。 - Tom Hawtin - tackline