展开全部
问问题要把自己疑惑的地方明确的说出来,不然谁知道你想问什么。
lock.notify();作用是唤32313133353236313431303231363533e59b9ee7ad9431333332626139醒等待的线程。
lock.wait();作用是使当前线程进入等待,一直到该lock被notify
你执行以下下面的代码就明白了。public class PrintNum {
private byte[] lock = new byte[0];
PrintThread a = new PrintThread("a");
PrintThread b = new PrintThread("b");
public void demo() {
a.start();
b.start();
}
public void printState(){
System.out.println("a state:"+a.getState());
System.out.println("b state:"+b.getState());
}
class PrintThread extends Thread {
public PrintThread(String name) {
this.setName(name);
}
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i
printState();//控制台输出线程状态
lock.notify();//位置1,程序可正常执行结束
if (i % 10 == 0 && 0 != i) {
try {
//lock.notify();
//位置2,程序执行到a:99,b:99后无法正常结束
lock.wait();
//位置3,程序执行到a:9,b:9后无法继续执行
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.getName() + ": " + i);
}
}
}
}
public static void main(String[] args) {
PrintNum printNum = new PrintNum();
printNum.demo();
}
}