iT邦幫忙

0

JAVA 多執行緒的問題

最近正在學多執行緒現在卡在一個地方是 A執行緒跑完以後B執行緒不會被喚醒以下是程式碼:

class Athread implements Runnable {
	public void run() {
		synchronized (this) {
			try {
				System.out.println("A點進入");
				for (int i = 1; i <= 10; i++) {
					System.out.println(i);
				}
				this.notifyAll();
			} catch (Exception e) {
			}
		
		}
	}
}
class Bthread implements Runnable {
	public void run() {
		synchronized (this) {
			try {
                this.wait();
				System.out.println("B點進入");
				for (int i = 1; i <= 10; i++) {
					System.out.println(i);
				}
			} catch (Exception e) {
			}
		}
	}
}

public static void main(String[] args) {
		Athread a = new Athread();
		Bthread b = new Bthread();
		Thread thr = new Thread(a);
		Thread thr1 = new Thread(b);
		thr.start();
		thr1.start();
	}

想請問各位我是否有地方理解錯了呢?
因為就我的理解是跑到notifyAll以後所有在wait()的執行緒都要被喚醒這樣
想請各位糾正一下
謝謝各位

fillano iT邦超人 1 級 ‧ 2020-03-16 10:31:55 檢舉
你的觀念有問題啦:

1. wait(), notify, notifyAll()是設計來同步用的,重點是同步
2. 所以如果需要的是去等待其他物件到他把事情做完,這時呼叫wait()
3. 其他物件做完時,就用notify()來通知呼叫他wait()的物件,這樣呼叫他wait的物件才會離開wait狀態
4. synchronized區塊的參數,放的是要同步的那個其他物件

你這樣寫就把自己鎖住了XD
好的謝謝教宗大大看來我還要重新理解這塊
讓我再消化一下
謝謝回覆~
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答