爲什麼通常線程樣本將很多代碼放在同步塊中。根據我在以下情況下同步的理解是隻用於鎖定b。對於等待和通知:瞭解在java中同步
主要類的ThreadA:
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
System.out.println(Thread.currentThread().getName());
}
}
}
和類ThreadB:
class ThreadB extends Thread {
int total;
public void run() {
synchronized(this)
{
System.out.println();
for(int i=0;i<100;i++)
{
System.out.println(Thread.currentThread().getName());
total += i;
}
notify();
}
}
}
會有什麼改變,如果我把wait
和notify
寫入區塊:
class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB();
b.start();
try {
System.out.println("Waiting for b to complete...");
synchronized(b) { b.wait();}
} catch (InterruptedException e) {}
System.out.println("Total is: " + b.total);
System.out.println(Thread.currentThread().getName());
}
}
但在這種特殊情況下,不同步總計+ = i是安全的,因爲沒有人會編輯它,並且根據代碼,只有在通知後纔會讀取,而不會編輯總數。我錯了? – vico
你的意思是我可以寫'b.wait();'而不是'synchronized(b){b.wait();}'? – vico