我有一个线程,我需要设置它在监听还是待机时的状态

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

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

最佳答案

不,这样做:

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

关于java - Java:这种方法线程安全吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27190137/

10-10 10:40