使用局部变量来避免竞争条件

时间:2015-10-17 08:43:07

标签: java multithreading

我有以下Runnable实施:

public class Example implements Runnable
{
    private Thread runThread = null;

    // Runs in its own thread
    @Override
    public void run() {
        assert runThread == null;  // must not call run() twice
        runThread = Thread.currentThread();
        try {
            while (!Thread.currentThread().isInterrupted()) {
                // do something
            }
        } finally {
            runThread = null;
        }
    }

    // Might be called from another thread
    public void stop() {
        Thread t = runThread;   // use temporary variable to avoid race condition with run()
        if (t != null) {
            // without the temporary variable, the run() thread could be set to null at this point
            t.interrupt();
        }
    }
}

我对此代码有两个问题:

  1. 使用临时局部变量存储可能被另一个线程设置为null的对象是否有效,或者我是否需要在此处进行其他同步?
  2. 这是为runnable提供停止机制的好方法,还是我应该让Example实例的所有者处理?

0 个答案:

没有答案