一、Thread.stop()
官方不推荐,Because it is inherently unsafe. 二、方式一1. 线程类示例public class ThreadT1 implements Runnable { private Thread threadThis; public void start() { threadThis = new Thread(this); threadThis.start(); } public void stop() { threadThis = null; } public void run() { Thread thisThread = Thread.currentThread(); while (threadThis == thisThread) { System.out.println("lalala~ "); // DO YOUR WORK ! } System.out.println("stopped!!!"); }}
ThreadT1 th1 = new ThreadT1();th1.start(); //新建线程并启动th1.stop(); //停止这个线程
public class ThreadT2 extends Thread { private boolean stop = false; public void stopByMark() { stop = true; } public void run() { while (!stop) { System.out.println("lalala~ "); // DO YOUR WORK ! } System.out.println("stopped!!!"); }}
ThreadT2 th2 = new ThreadT2();th2.start(); //新建线程并启动th2.stopByMark(); //停止这个线程
public void run(){ try { Thread.sleep(5000); } catch (InterruptedException e) { //必须存在捕获InterruptedException的方法,且发生了该 抛出就调用stop方法。 e.printStackTrace(); stopByMark(); }}