1、使用stop()方法,已被弃用。原因是:stop()是立即终止,会导致一些数据被到处理一部分就会被终止,而用户并不知道哪些数据被处理,哪些没有被处理,产生了不完整的“残疾”数据,不符合完整性,所以被废弃。So, forget it!
2、使用volatile标志位
看一个简单的例子:
首先,实现一个Runnable接口,在其中定义volatile标志位,在run()方法中使用标志位控制程序运行
public class MyRunnable implements Runnable {
public volatile boolean flag = true;
public void run() {
System.out.println("第" + Thread.currentThread().getName() + "个线程创建");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (flag) {
}
System.out.println("第" + Thread.currentThread().getName() + "个线程终止");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
然后,在main()方法中创建线程,在合适的时候,修改标志位,终止运行中的线程。
public class TreadTest {
public static void main(String[] arg) throws InterruptedException {
MyRunnable runnable = new MyRunnable();
for (int i = 1; i <= 3; i++) {
Thread thread = new Thread(runnable, i + "");
thread.start();
}
Thread.sleep(2000L);
System.out.println("——————————————————————————");
runnable.flag = false;
}
}
最后,运行结果,如下:
第1个线程创建
第2个线程创建
第3个线程终止
第1个线程终止
第2个线程终止