文章目录
本文以JDK1.8为例,进行测试
如何终止一个线程的执行?
1.stop方法
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
for(int i = 0; i <10 ; i++){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("i="+i);
}
});
t1.start();
TimeUnit.SECONDS.sleep(2);
t1.stop();
}
stop方法已经过时了
2.suspend
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
for(int i = 0; i <10 ; i++){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("i="+i);
}
});
t1.start();
TimeUnit.SECONDS.sleep(2);
t1.suspend();
TimeUnit.SECONDS.sleep(3);
t1.resume();
}
suspend也已经过时
3.使用volatile设置标志
static volatile boolean Running = true;
public static void main(String[] args) {
Thread t1 = new Thread(()->{
while(Running){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("正在运行...");
}
System.out.println("t1 结束....");
});
t1.start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//设置false
Running = false;
4.interrupt 中断线程
public static void main(String[] args) {
Thread t1 = new Thread(()->{
while(!Thread.interrupted()){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("interrupted");
}
System.out.println("t1线程结束...");
});
t1.start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
t1.interrupt();
}
5.Interrupt和LockSupport结合使用
public static void main(String[] args) {
Thread t = new Thread(() -> {
System.out.println("开始执行...");
LockSupport.park(); //线程阻塞
System.out.println("执行结束...");
});
t.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
t.interrupt();
}