java 休眠一个线程,直到另一个线程参加一个事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/121762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:06:13  来源:igfitidea点击:

Sleep a thread until an event is attended in another thread

javaandroidmultithreading

提问by Lucas S.

I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.

我在一个 Android 应用程序中有两个线程,一个是视图线程,另一个是工作线程。我想要做的是,使工作线程休眠,直到视图线程终止对 onDraw 方法的处理。

How i can do this? is there any wait for the signal or something?

我怎么能做到这一点?有没有等待信号之类的?

回答by Paul Brinkley

Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this:

在两个线程之间共享一个 java.lang.Object,其唯一目的是告诉工作线程何时可以继续工作。每当工作线程到达应该休眠的点时,它会执行以下操作:

stick.wait();

When the view thread finishes its onDraw work, it calls this:

当视图线程完成其 onDraw 工作时,它会调用:

stick.notify();

Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block:

请注意视图线程拥有对象上的监视器的要求。在您的情况下,使用一个小的同步块来强制执行这应该相当简单:

void onDraw() {
  ...
  synchronized (stick) {
    stick.notify();
  }
} // end onDraw()

Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written.

有关这些方法的 java.lang.Object(和 notifyAll,以防万一),请参阅 javadoc;他们写得很好。

回答by skaffman

If you want a higher-level concurreny API (with things like Barriers), you could try the backport of the java 5 concurrency API, which works on java 1.3 and above, and may work on Android. The likes of Object.wait/notify will work, but they can be a bit terse.

如果您想要更高级别的并发 API(带有 Barriers 之类的东西),您可以尝试向后移植 java 5 concurrency API,它适用于 java 1.3 及更高版本,并且可能适用于 Android。Object.wait/notify 之类的可以工作,但它们可能有点简洁。

Backport-util-concurrent

Backport-util-concurrent