Java高并发Stop()和Interrupt()的区别

1.stop()方法在现在JDK中不推荐使用,原因是stop()方法过于暴力,强行把执行到一半的线程终止,可能会引起一些数据不一致的问题。因此在使用stop()方法时需要自行决定线程何时退出!
public class TestThread01 extends Thread{
	volatile boolean stopme = false;
	public TestThread01() {
		stopme = true;
	}
	@Override
	public void run() {
		while(true) {
			if(stopme) {
				System.out.println("exit by stop me");
				break;
			}
			synchronized (xxx) {
			}
		}
	}
}
2.线程中断:

Thread.interrupt() //中断线程
Thread,isInterrupted()判断是否被中断
Thread.interrupted()判断是否被中断,并清除当前中断状态

中断的功能比stop()更为强劲,可以停止wait()方法和sleep()方法

你可能感兴趣的:(多线程)