首先肯定是不能用Thread的stop()方法的,因为此方法是非常不安全的,而且已经被废弃了,那么在这里就给出一种官方的推荐方案。 private static Thread mThread;
private static Thread mThread;
static StringMain.MyRunnable mRunnable = new StringMain().new MyRunnable();
public static void main(String[] args) {
System.out.println("A");
mThread = new Thread(mRunnable);
mThread.start();
// 2秒后停止线程
try {
Thread.sleep(2000);
//手动停止
mRunnable.destory();
mThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public class MyRunnable implements Runnable {
public void destory() {
mThread = null;
}
@Override
public void run() {
Thread thread = Thread.currentThread();
//当mThread被赋值为空时就会终止执行了,run方法结束,线程停止
while (mThread == thread) {
System.out.println("继续···");
}
}
}
主要办法就是在run方法中进行while判断,当要退出时就跳出循环即可。调用join方法主要是为了让线程终止后去执行其后的代码,也可不用调用。
关于Thread的stop()为何被抛弃以及不安全请见官网解释: http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html