Wait() notify()同步

Wait() notify()同步,第1张

Wait()/ notify()同步

对象监视器锁需要执行相同锁的单个引用。

在你的榜样,你是

waiting
对的一个实例
Thread
,但使用
notify
Runnable
。相反,您应该使用单个通用锁定对象…例如

public class Tester {    public static final Object LOCK = new Object();    public static void main(String[] args) {        MyRunnable r = new MyRunnable();        Thread t = new Thread(r);        t.start();        synchronized (LOCK) { try {     System.out.println("wating for t to complete");     LOCK.wait();     System.out.println("wait over"); } catch (InterruptedException e) {     e.printStackTrace(); }        }    }    public static class MyRunnable implements Runnable {        public void run() { System.out.println("entering run method"); synchronized (LOCK) {     System.out.println("entering syncronised block");     LOCK.notify();     try {         Thread.currentThread().sleep(1000);     } catch (InterruptedException e) {         e.printStackTrace();     }     System.out.println("leaving syncronized block"); } System.out.println("leaving run method");        }    }}

输出…

wating for t to completeentering run methodentering syncronised blockleaving syncronized blockwait overleaving run method

wait over
leaving run method
可能根据线程调度更改位置。

您可以尝试将睡眠排除在

synchronized
障碍之外。这将释放监视器锁定,从而允许该
wait
部分继续运行(因为在锁定释放之前它无法启动)

    public static class MyRunnable implements Runnable {        public void run() { System.out.println("entering run method"); synchronized (LOCK) {     System.out.println("entering syncronised block");     LOCK.notify();     System.out.println("leaving syncronized block"); } try {     Thread.currentThread().sleep(1000); } catch (InterruptedException e) {     e.printStackTrace(); } System.out.println("leaving run method");        }    }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5439481.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存