一.先来看一种强制终止线程:
这种方式存在很大的缺点:容易丢失数据。因为这种方式是直接将线程杀死了,线程没有保存的数据将会丢失。不建议使用。
public class ThreadTest09 {
public static void main(String[] args) {
Thread t=new Thread(new MyRunnable3());
t.setName("t");
t.start();
//模拟5秒
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//强行终止
t.stop();//已过时,不建议使用
}
}
class MyRunnable3 implements Runnable{
@Override
public void run() {
for (int i=0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"--->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
二.合理终止线程的方式:
class MyRunnable4 implements Runnable{
boolean run=true;
@Override
public void run() {
for (int i=0;i<10;i++){
if (run){
System.out.println(Thread.currentThread().getName()+"---->"+i);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
//终止当前线程
return;
}
}
}
}
Thread t=new Thread(r);
t.setName("t");
t.start();
//模拟五秒
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//合理终止线程
// 什么时候想要终止t的执行,修改标志位false就可以了
r.run=false;