1、使用Interrupt来通知
while (!Thread.currentThread().isInterrupted() && more work to do) { do more work }首先通过 Thread.currentThread().isInterrupt() 判断线程是否被中断,随后检查是否还有工作要做。
public class StopThread implements Runnable {
@Override
public void run() {
int count = 0;
while (!Thread.currentThread().isInterrupted() && count < 1000) {
System.out.println("count = " + count++);
}
}
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new StopThread());
thread.start();
Thread.sleep(5);
thread.interrupt();
}
}2、使用volatile标志一个字段,通过判断这个字段true/false退出线程
点触小程序是有南昌点触科技有限公司研发,我公司是国家级高新技术企业,本套源码是国内首家应该到目前为止也是独家用.netcore开发的小程序平台站,公司有三个开发组同时做小程序平台开发,一个php开发组,一个java开发组,一个.netcore开发组,三组独立并行开发。目前投入上线运营的未php版本,其他两组均是做封闭性开发测试,不对外公布。秉着互联网的合作,共享,开放,共赢的原则,我们将本套.NE
/**
* 描述: 演示用volatile的局限:part1 看似可行
*/
public class WrongWayVolatile implements Runnable {
private volatile boolean canceled = false;
@Override
public void run() {
int num = 0;
try {
while (num <= 100000 && !canceled) {
if (num % 100 == 0) {
System.out.println(num + "是100的倍数。");
}
num++;
Thread.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
WrongWayVolatile r = new WrongWayVolatile();
Thread thread = new Thread(r);
thread.start();
Thread.sleep(5000);
r.canceled = true;
}
}










