Java 线程停止暂停和继续
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 线程停止暂停和继续相关的知识,希望对你有一定的参考价值。
Thread 类中停止线程的方法有 stop(),暂停和继续线程的方法有 suspend() 和 resume()。然而这些方法已经被废弃了。
异常法停止线程
上代码:
public class Test { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); } } class MyThread extends Thread { @Override public void run(){ boolean flag = true; while (flag) { if (this.isInterrupted()) { System.out.println("线程即将停止"); try { throw new InterruptedException(); } catch (InterruptedException e) { flag = false; } } } System.out.println("已经跳出循环,线程停止"); } }
打印输出:
线程即将停止 已经跳出循环,线程停止
run 方法执行完,线程自然就结束了。
使用 return 停止线程
public class Test2 { public static void main(String[] args) { MyThread2 thread = new MyThread2(); thread.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); } } class MyThread2 extends Thread { @Override public void run() { while (true) { if (this.isInterrupted()) { System.out.println("线程停止"); return; } } } }
打印输出:
线程停止
线程暂停和继续
线程暂停、继续和停止,上代码:
public class Test { public static void main(String[] args) { MyThread thread = new MyThread(); thread.start(); try { Thread.sleep(1); thread.mySuspend(); Thread.sleep(1); thread.myResume(); Thread.sleep(1); thread.myStop(); } catch (Exception e) { e.printStackTrace(); } } } class MyThread extends Thread { private int counts = 0; private int status = 1; private final int SUSPEND = -1; private final int RUNNING = 1; @Override public void run() { boolean flag = true; while (flag) { if (this.isInterrupted()) { System.out.println(++counts + " - 线程即将停止"); try { throw new InterruptedException(); } catch (InterruptedException e) { flag = false; } } else if (status == SUSPEND) { System.out.println(++counts + " - 线程暂停"); } else if (status == RUNNING) { System.out.println(++counts + " - 线程仍在继续"); } } System.out.println(++counts + " - 已经跳出循环,线程停止"); } public void mySuspend() { status = SUSPEND; } synchronized public void myResume() { status = RUNNING; this.notifyAll(); } public void myStop() { this.interrupt(); } }
打印输出:
1 - 线程仍在继续 2 - 线程暂停 3 - 线程暂停 ... 42 - 线程暂停 43 - 线程暂停 44 - 线程仍在继续 45 - 线程仍在继续 46 - 线程仍在继续 ... 87 - 线程仍在继续 88 - 线程仍在继续 89 - 线程仍在继续 90 - 线程仍在继续 91 - 线程即将停止 92 - 已经跳出循环,线程停止
以上是关于Java 线程停止暂停和继续的主要内容,如果未能解决你的问题,请参考以下文章
ExecutorService线程池中怎么去暂停和继续一个线程
java中ExecutorService的线程池如何暂停所有的任务和继续所有的任务? 有这样的函数吗?