Return停止线程: 使用interrupt()和return结合也可以实现停止线程的效果.不过还是建议使用“抛异常“的方法,因为在catch块中可以将异常向上抛,使线程停止的事件得以传播. public class ReturnInterruptThread extends Thread{ @Override public void run() { while (true){ if (this.isInterrupted()){ System.out.println("Stop thread…
package com.cky.thread; /** * Created by edison on 2017/12/3. */ public class MyThread12 extends Thread{ @Override public void run() { super.run(); for (int i = 0; i < 50000; i++) { if (Thread.interrupted()) { System.out.println("子线程已经停止了,我要退出&quo…
本文将介绍jdk提供的api中停止线程的用法. 停止一个线程意味着在一个线程执行完任务之前放弃当前的操作,停止一个线程可以使用Thread.stop()方法,但是做好不要使用它,它是后继jdk版本中废弃的或者将不能使用的方法,大多数停止一个线程的操作使用Thread.interrupt()方法. 1.本实例将调用interrupt()方法来停止线程,创建MyThread.java,代码如下: package com.lit.thread006; public class MyThread ext…
1.异常法 public class MyThread extends Thread { @Override public void run() { super.run(); try { for (int i = 0; i < 5000000; i++) { if(this.interrupted()){ System.out.println("我要停止了....."); throw new InterruptedException(); \\抛出异常 } System.out.…
package charpter10; public class Processor implements Runnable { @Override public void run() { for (int i = 0; i <= 100; i++) { System.out.println("中断标记位:" + Thread.currentThread().isInterrupted()); System.out.println("状态:" + Thread…
在沉睡中停止线程会抛出异常 public class SleepInterruptDemo extends Thread { public void run() { super.run(); try { for (int i = 0; i < 500000; i++) { System.out.println("i=" + (i + 1)); } System.out.println("run begin"); Thread.sleep(2000); Syst…
调用interrupt方法仅仅是在当前线程中打了一个停止的标记,并不是真正停止线程. this.interrupted() :测试当前线程是否已经中断,执行后具有将状态标志清除为false的功能 isInterrupted() : 测试线程Thread对象是否已经是中断状态,但不清除状态标志. public class InterruptDemo extends Thread{ public void run(){ super.run(); try{ for(int i =0;i< 5000…
异常法停止线程: public class RealInterruptThread extends Thread { @Override public void run() { try { for (int i = 0; i < 5000000; i++) { if (Thread.interrupted()) { System.out.println("Thread is interrupted status, I need exit."); throw new Interru…