在 synchronized 块里, 使用 wait 和 notify, 让 多个线程交替执行.
wait 和 notify 比较:
相同的是:
都会阻塞线程.
不同的是:
sleep 是 Thread 的 static 方法, wait 不是 线程类 Thread 的方法, 而是属于 Object.
sleep 在任何地方都可以调用, 而 wait 只在 synchronized 块里使用.
wait 会释放当前锁, sleep 不会.
notify() 只唤醒一个 wait 的线程, 哪个优先级高, 哪个先唤醒.
问题: 是谁调用的 wait,notify? 是 this, 当前类.
- public class CommThread {
- public static void main(String[] args) {
- Number number = new Number();
- new Thread(number).start();
- new Thread(number).start();
- }
- }
- class Number implements Runnable{
- private int num = 1;
- @Override
- public void run() {
- while(true){
- synchronized (this) {
- if(num<10){
- notifyAll();
- System.out.println(Thread.currentThread().getName() + ":" +num);
- num++;
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }else{
- // break;
- System.exit(1);
- }
- }
- }
- }
- }
来源: http://www.bubuko.com/infodetail-3219203.html