强行终止线程的执行
- .stop()方法(已弃用)
这种方式有一个很大的缺点:容易丢失数据,因为直接将进程杀死了,
线程没有保存的数据会丢失
public class ThreadTest09 {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable3());
t.setName("t");
t.start();
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
t.stop();
}
}
class MyRunnable3 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "————>begin");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "————>" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "————>over");
}
}
合理终止线程的执行
- 设立一个布尔标记,通过改变标记的方式终止线程
- 可以在else方法体处进行数据的保存等处理
public class ThreadTest10 {
public static void main(String[] args) {
MyRunnable4 run4 = new MyRunnable4();
Thread t = new Thread(run4);
t.setName("t");
t.start();
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
e.printStackTrace();
}
run4.run = false;
}
}
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(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
return;
}
}
}
}