编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

如何暂停线程执行:How to pause Thread execution

Shrish Sharma 线程 2022-5-13 10:39 38人围观

腾讯云服务器
如何暂停线程执行的处理方法

如何暂停某些线程的执行.我有线程t,我有两个按钮,暂停和继续.暂停时,我需要暂停线程执行,然后继续从之前停止的位置开始线程开始执行.在听众中放什么?

How to pause execution of some Thread. I have Thread t and I have two buttons, PAUSE and CONTINUE. On pause I need to pause thread execution and on continue to thread start execution from point where stoped before. What to put in listeners?

问题解答

Java中的线程是协作的,这意味着您不能强制线程停止或暂停,而是向线程发送所需的信息和线程(=逻辑)本身完成.

Threading in Java is cooperative, which means you can not force the thread to stop or pause, instead you signal to the thread what you want and thread (= your logic) does it itself.

为此使用同步,wait()和notify().

Use synchronized, wait() and notify() for that.

  1. 在要停止的线程中创建一个原子标记(例如boolean字段).可停止线程在循环中监视此标志.循环必须在 synchronized 块内.
  2. 当您需要停止线程(单击按钮)时,请设置此标志.
  3. 线程看到标志已设置,并在公共对象(可能是本身)上调用 wait().
  4. 要重新启动线程时,请重置标志并调用 commonObject.notify().

这篇关于如何暂停线程执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^