且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何暂停线程执行

更新时间:1970-01-01 07:56:12

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