weixin_43306301
2019-07-26 12:20
采纳率: 100%
浏览 571
已采纳

线程同步锁中为什么锁对象和wait()或notify()的对象要一致?

线程同步锁中为什么锁对象和wait()或notify()的对象要一致?

package com.dtz.ThreadAndGui.day25.Thread;

import com.dtz.Thread.day24.syn.Demo1_synchronized;

public class Demo1_Notify {


public static void main(String[] args) {
    final Demo d = new Demo();
    new Thread(){
        @Override
        public void run() {
            while(true) {
                try {
                    d.print1();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }.start();

    new Thread(){
        @Override
        public void run() {
            while(true) {
                try {
                    d.print2();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

}


class Demo {    
    private int flag = 1;
    public void print1() throws InterruptedException {
    synchronized (this) {       //这里是Demo.class的话,下面的wait()和notify()会抛异常
    if (flag != 1) {
        this.wait();
    }
    System.out.print("a");
    System.out.print("a");
    System.out.print("a");
    System.out.println();
    flag = 2;
    this.notify();          
    }
}

public void print2() throws InterruptedException {
        synchronized (this) {
            if (flag != 2) {
                this.wait();
            }
            System.out.print("b");
            System.out.print("b");
            System.out.print("b");
            System.out.print("b");
            System.out.print("b");
            System.out.println();
            flag = 1;
            this.notify();
        }
    }
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

相关推荐 更多相似问题