有没有人看到这个线程模式有任何问题? [英] does anyone see any issues with this thread pattern?

查看:114
本文介绍了有没有人看到这个线程模式有任何问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is a simple thread pattern that I use when writing a class that needs just one thread, and needs to a specific task.

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

The usual requirements for such a class are that it should be startable, stopable and restartable. Does anyone see any issues with this pattern that I use?

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

我正在寻找周围的评论如果我遗漏了什么,或者有更好的方法来写这个。

I am looking for comments around if I am missing something, or if there is a better way to write this.

推荐答案

那么,这个类本身不是线程安全。只要在代码中记录和观察到这一点,这就不一定是个问题。如果不是,你可能会失去对并行运行的Thread对象的引用,如果两个消费者同时进入start()方法。

Well, the class itself is not thread safe. That's not necessarily a problem as long as that's documented and observed in code. If it's not you could lose references to Thread objects that will run in parallel, if two consumers get inside the start() method at the same time.

用作信号量的标志当然也应该变得不稳定。

Flags used as semaphores should also of course be made volatile.

该类的API有点奇怪。你实现了Runnable,对其他类说使用我的run方法来调用我,然后模仿完整Thread对象的start方法。您可能希望在内部类中隐藏run方法。否则,打算如何使用该对象有点令人困惑。

The API of the class is a little bit strange. You implement Runnable, saying to other classes "use my run method to invoke me" but then mimic the start method of a full Thread object. You may want to hide the run method inside an inner class. Otherwise it's somewhat confusing how one is intended to use the object.

和往常一样,任何涉及单词 new Thread()的模式而不是使用池在摘要中有点怀疑。需要知道你实际上在做什么才能真正对此进行智能评论。

And as always, any pattern that involves the words new Thread() rather than using a pool is somewhat suspect in the abstract. Would need to know about what you're actually doing with it to really comment intelligently on that though.

这篇关于有没有人看到这个线程模式有任何问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆