天天看點

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();
    }
}      

使用 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();
    }
}