栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Wait()/ notify()同步

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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");        }    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/463985.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号