如何暂停线程执行 [英] How to pause Thread execution

查看:51
本文介绍了如何暂停线程执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何暂停某些线程的执行.我有线程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().

这篇关于如何暂停线程执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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