0
点赞
收藏
分享

微信扫一扫

Java并发编程核心_如何关闭一个线程

捕获中断信号关闭线程

package com.neu.day02;

import java.util.concurrent.TimeUnit;

/**
* @Author yqq
* @Date 2022/03/27 18:50
* @Version 1.0
*/
public class Thread05 {
public static void main(String[] args) throws InterruptedException{
Thread t = new Thread(){
@Override
public void run() {
System.out.println("I will start work.");
while (!this.isInterrupted()){
System.out.println("I an working");
}
System.out.println("I will be exiting");
}
};
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown");
t.interrupt();
}
}

Java并发编程核心_如何关闭一个线程_sed

使用 volatile 开关控制

package com.neu.day02;

import java.util.concurrent.TimeUnit;

/**
* @Author yqq
* @Date 2022/03/27 19:02
* @Version 1.0
*/
public class Thread06 {
public static void main(String[] args) throws InterruptedException{
Mytask t = new Mytask();
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown");
t.close();
}
}

class Mytask extends Thread{

private volatile boolean closed = false;

@Override
public void run() {
System.out.println("I will start work.");
while (!closed && isInterrupted()){
System.out.println("I an working");
}
System.out.println("I will be exiting");
}
public void close(){
this.closed = true;
this.interrupt();
}
}

Java并发编程核心_如何关闭一个线程_sed_02


举报

相关推荐

0 条评论