1、Thread.stop()(相当暴力,但已废弃)
2、Thread.interrupt()(很暴力,在catch中处理线程停掉前的操作)
3、共享的条件变量
例:
public class MyThreadClass {
public static void main(String[] args) {
StuThread stuThread = new StuThread();
stuThread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stuThread.stopMe();
}
}
class StuThread extends Thread {
public volatile boolean finished = false; // ① volatile条件变量
public void stopMe() {
finished = true; // ② 发出停止信号
// interrupt();
}
@Override
public void run() {
while (!finished) { // ③ 检测条件变量
// do dirty work // ④业务代码
System.out.println(new Date());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}