有没有人看到这个线程模式有任何问题?

rou*_*ble 3 java multithreading design-patterns

这是一个简单的线程模式,我在编写只需要一个线程的类时使用,并且需要特定的任务.

这类的通常要求是它应该是可启动的,可停止的和可重启的.有没有人看到我使用这种模式的任何问题?

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我遗漏某些东西,或者有更好的方法来写这个,我正在寻找评论.

Gru*_*eck 6

我建议不要直接使用Thread类.自Java 5以来可用的Executors框架简化了线程中涉及的许多问题.我们的想法是,您的类将执行所需的任务,并且所有线程功能都由Executor管理,从而为您节省处理线程复杂性的工作.

可以在此处找到Java Executors框架上的一个好的介绍.