Java:这种方法线程安全吗?

时间:2014-11-28 13:51:52

标签: java multithreading

我有一个线程,我需要设置何时正在收听或待机,因为我已经定义了

public static enum ListenerState { STAND_BY, LISTENING }; 

和方法

public void setState(ListenerState state){
    this.state = state;
}

现在,在主循环中我以这种方式检查状态

@Override
public void run() {
    while (!Thread.interrupted()) {
        try {
            if (state==ListenerState.LISTENING){
               // do my job
            }
            else{
                Thread.sleep(300);
            }
        }
    }
}

这种方法是否是线程安全的?

3 个答案:

答案 0 :(得分:3)

不,那样做:

class MyThread implements Runnable {

    private volatile ListenerState state;

    public synchronized void setState(ListenerState state){
       this.state = state;
    }

    @Override
    public void run() {
       while (true) {
         try {
            if (state==ListenerState.LISTENING){
              // do my job
            } else{
              Thread.sleep(300);
            }
          } catch (IterruptedException ex){
            return; 
          }
        }
    }
}

答案 1 :(得分:2)

您可以在此处找到答案:Do I need to add some locks or synchronization if there is only one thread writing and several threads reading?

一句话:最好将volatile关键字添加到州。

答案 2 :(得分:1)

如果状态可以被不同的线程更改或读取,那么您需要同步块以进行读写方法。或者作为更好的方式,使用AtomicBoolean。它是摆脱同步块并使其线程安全的完美对象

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html