第一類:這些類是線程安全的嗎?
class Main1 {
private ExecutorService service = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
Main1 m = new Main1();
m.start();
}
public void start() {
final MyObject obj = new MyObject();
obj.doSomeCalculation();// after this point not to modify obj in main thread
service.submit(new Runnable(){
public void run() {
obj.doSomething(); // is it threadsafe doing this?
}
});
}
}
二等:
class Main2 {
private ExecutorService service = Executors.newFixedThreadPool(4);
public static void main(String[] args) {
Main2 m = new Main2();
m.start();
}
public void start() {
class Job implements Runnable {
public MyObject obj;
public void run() {
obj.doSomething(); // is it threadsafe doing this?
}
}
Job job = new Job();
job.obj.doSomeCalculation(); // after this point not to modify obj in main thread
service.submit(job);
}
}
是Main1
和Main2
線程? Main1和Main2對線程安全有不同的意義嗎?
更新: doSomeCalulation()和doSomething()都沒有任何鎖定或同步塊。我想知道doSomething()是否總能讀取doSomeCalculation()更改爲obj的正確狀態
我無法用英語表達良好,您的答案確實非常好。非常感謝。 – Jarod
不客氣。 –