终止线程
在java里面,终止线程的方式有三种
①使用全局自定义的变量来终止线程
②使用线程提供的终止方法 interrupt 来终止线程
③使用线程提供的方法 stop 来终止线程(弃用,终止之后,未释放资源,有安全隐患)
这里直接结合代码演示
第一种
public class ThreadDemo6 {
public static boolean flag=false;
public static void main(String[] args) throws InterruptedException {
//转账线程
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
while(!flag){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("正在进行转账!");
}
System.out.println("终止转账!");
}
});
t1.start();
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(410);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("有内鬼,停止交易!");
flag=true;
}
});
t2.start();
t1.join();
t2.join();
}
}
根据代码可知,转账可以进行四次,然后终止,但是在终止之后还进行了一次转账,就说明定义全局变量来控制线程终止会执行完当前手头的任务之后再终止
第二种
①使用Thread.interrupted()方法
这里真正让线程结束的其实是break,最后调用的Interrupt()方法只是修改了Thread.interrupted()的状态,默认false,修改为true。
public class ThreadDemo7 {
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.interrupted()){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
//e.printStackTrace();
break;
}
System.out.println("正在进行转账!");
}
System.out.println("终止转账!");
}
});
t1.start();
Thread.sleep(310);
System.out.println("有内鬼,停止交易!");
t1.interrupt();
}
}
在收到终止指令之后会立马结束执行
②使用Thread.currentThread().isInterrupted()
public class ThreadDemo8 {
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
System.out.println("正在进行转账!");
}
System.out.println("终止转账");
}
});
t1.start();
Thread.sleep(5);
System.out.println("有内鬼,终止交易!");
t1.interrupt();
}
}
那么第①种和第②种方式有什么区别呢?
第①种在执行判断线程终止为true之后,就会将状态重置为false状态
而第②不会复位线程的终止状态
代码中的interrupt()的作用就是用来修改线程终止状态的
第三种
很明显已经被弃用了
😄