wait() 无限制等待下去 wait(1000) 等待1s
b.wait();的意思是临时释放锁,并阻塞当前线程 直到notify 或(notifyAll )
notify()所在的同步块运行完之后,wait所在的线程就可以继续执行.
notify() 和 wait() 需要在 synchronized 之中
package test;
class Ticker extends Thread {
int tickets=50;
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
Ticker test = new Ticker();
Thread thread1 = new Thread(test);
Thread thread2 = new Thread(test);
thread1.start();
thread2.start();
System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
}
public void run() {
System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
while(tickets>0){
output();
}
System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
}
public synchronized void output(){
//待注销开始 如果注销这段 结果会变化
notify();
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
//待注销结束
System.out.println(tickets + " " + Thread.currentThread().getName());
tickets--;
}
}
结果如下:
main 线程运行开始!
main 线程运行结束!
Thread-1 线程运行开始!
Thread-2 线程运行开始!
50 Thread-1
49 Thread-2
48 Thread-1
47 Thread-2
46 Thread-1
45 Thread-2
如果把 待注销开始和待注销结束之间的代码注销后可能出现结果如图:
main 线程运行开始!
main 线程运行结束!
Thread-2 线程运行开始!
50 Thread-2
49 Thread-2
Thread-1 线程运行开始!
48 Thread-2
47 Thread-1
解释:1线程运行后到wait 一直到2线程notify后然后wait后 1线程继续运行,
1线程继续运行到notify然后wait 此时通知2线程 运行, 所以没有注销代码的时候会1、2线程交替运行。
这里只有两个线程,所以不用指定对象名后再notify