睡眠线程,直到事件出席了在另一个线程 [英] Sleep a thread until an event is attended in another thread

查看:94
本文介绍了睡眠线程,直到事件出席了在另一个线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个Android应用程序两个线程,一个是认为线程,另外一个工作线程。我想做的事就是睡觉工作者线程,直到观点线程终止的OnDraw方法的处理。

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

我可怎么办呢?有一个信号什么的等待?

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

推荐答案

共享的java.lang.Object两个线程,其唯一目的就是要告诉工作线程时,它可以继续开展工作的。每当工作线程达到一个点,它应该睡觉了,它这样做:

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:

stick.wait();

在视图线程完成其OnDraw中的工作,它调用这样的:

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

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()

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

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

这篇关于睡眠线程,直到事件出席了在另一个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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