Unsafe.park vs Object.wait [英] Unsafe.park vs Object.wait

查看:164
本文介绍了Unsafe.park vs Object.wait的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个关于 Unsafe.park Object.wait (以及相应的简历方法)的问题:

I have a couple of questions regarding Unsafe.park and Object.wait (and their corresponding resume methods):


  1. 一般应该使用哪一个?

  2. 哪一个有更好的性能?

  3. 使用 Unsafe.park 优于 Object.wait

  1. Which one should be used in general?
  2. Which one has better performance?
  3. Is there any advantage to using Unsafe.park over Object.wait?


推荐答案

如果您是应用程序员,则不应该使用这些方法中的任何一种。

You're not supposed to use either of these methods if you're an application programmer.

它们都太低了,容易搞砸而且不打算在图书馆外使用。

They are both too low level, easy to screw up and not meant to be used outside libraries.

为什么不尝试使用更高级别的构造,如java.util.concurrent.locks?

Why not try to use a higher level construct like java.util.concurrent.locks ?

回答你的问题。 park(...)直接在线程上工作。它将线程作为参数并将其置于休眠状态,直到在线程上调用unpark,除非已经调用了unpark。

To answer your question. park(...) works directly on the thread. It takes the thread as a parameter and puts it to sleep until unpark is called on the thread, unless unpark has already been called.

它应该比Object更快。 wait(),如果你知道需要阻塞/解除阻塞的线程,它会对监视器抽象进行操作。

It's supposed to be faster than Object.wait(), which operates on the monitor abstraction if you know which thread you need to block/unblock.

Btw unpark不是那么不安全如果在Java内部使用

Btw unpark is not really that Unsafe if used from inside Java:


public native void unpark(Object thread)

取消阻止给定的线程
在停车时被阻止,或者,如果没有被阻止,则导致后续呼叫
停车不阻止。注意:此操作不安全仅仅因为
调用者必须以某种方式确保线程没有被销毁。

Java(通常会有
线程的实时引用)调用时,通常不需要任何特殊功能来保证这一点,但这几乎不会自动,所以当从$调用时b $ b本机代码。

Unblock the given thread blocked on park, or, if it is not blocked, cause the subsequent call to park not to block. Note: this operation is "unsafe" solely because the caller must somehow ensure that the thread has not been destroyed. Nothing special is usually required to ensure this when called from Java (in which there will ordinarily be a live reference to the thread) but this is not nearly-automatically so when calling from native code.

这篇关于Unsafe.park vs Object.wait的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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