对象监视器锁需要执行相同锁的单个引用。
在你的榜样,你是
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"); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)