在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ Java wait釋放對象鎖

Java wait釋放對象鎖

 public class ThreadDemo {

    private void w() {
        synchronized (this) {
            System.out.println("wait start");
            try {
                this.wait();
                System.out.println("wait over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void n() {
        System.out.println("notify start");
        synchronized (this) {
            this.notifyAll();
            try {
                Thread.sleep(200);
                System.out.println("notify over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo demo = new ThreadDemo();
        demo.w();
        demo.n();
    }
}

控制臺只打印了wait start
為什么n方法進不去呢?

回答
編輯回答
懷中人

this.wait()讓線程一直在等待狀態(tài)

2017年12月1日 09:02
編輯回答
喵小咪

多線程,多線程,你都沒開多線程啊,你應該開辟線程來分別調(diào)用w方法和n方法。

2017年4月16日 10:20
編輯回答
萌小萌
class T1 implements Runnable{

    private ThreadDemo threadDemo;
    
    public T1(ThreadDemo threadDemo) {
        this.threadDemo = threadDemo;
    }

    public void run() {
        
        threadDemo.w();
    }
    
}
class T2 implements Runnable{

    private ThreadDemo threadDemo;
    
    public T2(ThreadDemo threadDemo) {
        this.threadDemo = threadDemo;
    }

    public void run() {
        
        threadDemo.n();
    }
    
}
public class ThreadDemo {

    public void w() {
        synchronized (this) {
            System.out.println("wait start");
            try {
                this.wait();
                System.out.println("wait over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public  void n() {
        System.out.println("notify start");
        synchronized (this) {
            this.notifyAll();
            try {
                Thread.sleep(200);
                System.out.println("notify over");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo threadDemo=new ThreadDemo();
        new Thread(new T1(threadDemo)).start();
        new Thread(new T2(threadDemo)).start();
        
       
    }
}
2017年5月27日 08:43