我从这里跟随例子
我已经修改为processCommand
-
private void processCommand() throws InterruptedException {
this.command = "xyz";
}
完整代码-
import java.util.logging.Level;
import java.util.logging.Logger;
public class WorkerThread implements Runnable {
private String command;
public WorkerThread(String s) {
this.command = s;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(Thread.currentThread().getName() + " Commad at start :" + command);
try {
processCommand();
} catch (InterruptedException ex) {
}
System.out.println(Thread.currentThread().getName() + " Command after processCommand : " + command);
}
private void processCommand() throws InterruptedException {
this.command = "xyz";
}
}
现在,我希望看到同步问题,对吧?基本上,当
System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
执行后,它可以获取值xyz
,对吗?但我从来没有看到它。我在 Thread.Sleep 中尝试了各种值。
那么在这种情况下,是什么使this.command = "xyz";
语句线程安全?
我以这种方式开始线程 -
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new WorkerThread("" + i);
executor.execute(worker);
}