LockSupport.park()可以代替Object.wait()吗? [英] Can `LockSupport.park()` replace `Object.wait()`?

查看:79
本文介绍了LockSupport.park()可以代替Object.wait()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在学习Java中的并发编程.我注意到Java 1.6中引入的 LockSupport.park() Object.wait()易于使用,这是 Object.wait()<的典型用法/code>就像

 //Thread1同步(锁定){while(条件!= true){lock.wait()}//做东西}//线程2同步(锁定){条件=真;lock.notify();} 

我想我可以像

那样使用 LockSupport.park()重写它

 //Thread1while(条件!= true){LockSupport.park();}//做东西//线程2条件=真;LockSupport.unpark(Thread1); 

通过使用 LockSupport.park(),乏味的 synchroinzed 块消失了.

我的问题是,我是否应该总是比 Object.wait()更喜欢 LockSupport.park()?在性能方面,有什么方面 Object.wait()比[code] LockSupport.park()更好的吗?

解决方案

wait/notify背后的思想是通知不是特定于线程的,通知者不必知道需要通知的特定线程,它只是告诉锁(或ReentrantLock的条件)它正在通知,锁和它们之间的OS调度程序决定谁接收通知.

我希望通知者在大多数时候都不想知道什么线程需要释放,因此等待/通知对于那些情况是一个更好的选择.使用停放/取消停放,您的代码必须了解更多信息,否则失败的机会就会更多.您可能会认为同步块很乏味,但是真正要乏味的是整理出某些情况,当某些东西本来应该停放的时候,这些东西就不会停放.

请注意,在您的第二个示例中,您的条件需要是易失性或原子性的,否则必须在线程间可见其更新.

Currently I'm learning concurrency programming in Java. I notice LockSupport.park() introduced in Java 1.6 is much easier than Object.wait() to use, a typical usage of Object.wait() is like

// Thread1
synchronized (lock) {
    while (condition != true) {
        lock.wait()
    }

    // do stuff
}

// Thread2
synchronized (lock) {
    condition = true;
    lock.notify();
}

And I think I can rewrite it using LockSupport.park() like

// Thread1
while (condition != true) {
    LockSupport.park();
}

// do stuff

// Thread2
condition = true;
LockSupport.unpark(Thread1);

By using LockSupport.park(), tedious synchroinzed block disappears.

My question is, should I always prefer LockSupport.park() than Object.wait()? Is there any aspect that Object.wait() does better than LockSupport.park() such as performance?

解决方案

The idea behind wait/notify is that the notifications are not thread-specific, the notifier doesn't have to know the specific thread that needs notifying, it just tells the lock (or condition, for a ReentrantLock) that it's notifying, and the lock and OS scheduler between them decide who gets the notification.

I would expect most of the time the notifier wouldn't want to have to know what thread needs unparking so wait/notify would be a better choice for those cases. With park/unpark your code has to know more and there will be more opportunities for failure. You may think a synchronized block is tedious but what will really be tedious is sorting out cases where something doesn't get unparked when it should have.

Note in your second example your condition needs to be volatile or Atomic or otherwise something where its updates are visible across threads.

这篇关于LockSupport.park()可以代替Object.wait()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆