最開始因?yàn)楂@取的lockSeq不是最新的,一直沒有正確的結(jié)果秕铛,導(dǎo)致誤判notifyAll只會(huì)喚醒一個(gè)線程约郁,通過對(duì)照api,并實(shí)際跟蹤仔細(xì)調(diào)試但两,找到問題鬓梅。
多線程debug還是很麻煩,step不能看到全局線程狀態(tài)谨湘,通過continue才解決問題己肮。
附上api
Screen Shot 2019-01-12 at 10.16.26 PM.png
public class ThreadSeq {
public static void main(String args[]) {
ResourceLock lock = new ResourceLock();
AThread threadA = new AThread(lock, "A", 0);
AThread threadB = new AThread(lock, "B", 1);
AThread threadC = new AThread(lock, "C", 2);
threadA.start();
threadB.start();
threadC.start();
}
}
class AThread extends Thread {
public static int THREAD_COUNT = 3;
private ResourceLock lock;
private String name;
private int threadSeq;
public AThread(ResourceLock lock, String name, int threadSeq) {
super(name);
this.lock = lock;
this.name = name;
this.threadSeq = threadSeq;
}
@Override
public void run() {
try {
synchronized(lock) {
for (;;) {
int lockSeq = lock.getThreadSeq() ;
// 這里要注意獲取的時(shí)候?qū)懙絯hile中,寫在前面導(dǎo)致是舊的值悲关,浪費(fèi)了一天的調(diào)試時(shí)間
while (lockSeq != threadSeq) {
lock.wait();
// 喚醒后獲取更新的值
lockSeq = lock.getThreadSeq();
}
System.out.println("------" + name + "------");
lockSeq = (lockSeq + 1) % 3;
lock.setCurSeq(lockSeq);
lock.notifyAll();
}
}
} catch(InterruptedException e) {}
}
}
class ResourceLock {
private int curSeq = 0;
public void setCurSeq(int curSeq) {
this.curSeq = curSeq;
}
public int getThreadSeq() {
return this.curSeq;
}
}