如何使线程从Java中的另一个线程休眠 [英] How to make a thread sleep from another thread in Java

查看:159
本文介绍了如何使线程从Java中的另一个线程休眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个执行线程(如Thread1和Thread2)。 Thread2正在监听特定事件,并且随着事件发生,它希望停止执行Thread1并触发一个动作。在完成该操作后,需要继续执行Thread1从其停止的位置。



我应该采取什么样的方法在Java中执行此操作? p>

解决方案

IMHO的干净方法是让Thread1定期轮询一些状态变量,看看是否被要求暂停。如果被要求暂停,那么它应该暂停它的执行,等待一些锁被释放。 Thread2应该通过更改共享状态变量的值来暂停,然后等待Thread1接受暂停请求,然后执行其动作并释放锁定Thread1正在等待。



简而言之,两个线程必须协作。没有办法,我知道如果没有协作,就能干净地暂停线程。


I have two threads of execution(say Thread1 and Thread2). Thread2 is listening for a particular event and as the event occurs it wants to stop execution of Thread1 and trigger an action. After it is done with the action it needs to continue the execution of Thread1 from where it stopped.

What kind of approach should I take to do this in Java?

解决方案

The clean way to do it, IMHO, is to make Thread1 regularly poll some state variable to see if it has been asked to pause. If it's been asked to pause, then it should suspend its execution, waiting for some lock to be released.

Thread2 should ask Thread1 to pause by changing the value of the shared state variable, then potentialy wait for Thread1 to accept the pause request, then execute its action and release the lock on which Thread1 is waiting.

In short, the two threads must collaborate. There is no way that I'm aware of to pause a thread cleanly without its collaboration.

这篇关于如何使线程从Java中的另一个线程休眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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