终止java线程的2种方法

本文介绍了一种在Java中优雅地停止线程的方法,通过使用volatile变量和interrupt方法,实现线程的平滑退出,避免了硬停止可能导致的资源泄露问题。

1、使用一个volatile的共享变量

2、使用interrupt方法

import java.util.concurrent.TimeUnit;

/**
 * ThreadTest
 */
public class ThreadTest implements Runnable {

    private volatile boolean stop = false;

    @Override
    public void run() {
        while (!stop) {
            System.out.println(Thread.currentThread().getName() + " is running...");
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("wake up from block");
                stop = true;
            }
        }
        System.out.println(Thread.currentThread().getName() + " is exiting...");
    }

    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        Thread t1 = new Thread(threadTest);
        t1.start();
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            //
        }

        // 1、使用 volatile共享变量
        threadTest.stop = true;

        // 2、使用interrupt方法
        System.out.println("Interrupt thread:" + t1.getName());
        t1.interrupt();
        try {
            TimeUnit.MILLISECONDS.sleep(3000);
        } catch (InterruptedException e) {
            //
        }
        System.out.println("Stopping application...");
    }

}

2种可能的运行结果:

Thread-0 is running...
Thread-0 is running...
Thread-0 is running...
Interrupt thread:Thread-0
Thread-0 is running...
wake up from block
Thread-0 is exiting...
Stopping application...

Thread-0 is running...
Thread-0 is running...
Thread-0 is running...
Interrupt thread:Thread-0
Thread-0 is running...
Thread-0 is exiting...
Stopping application...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值