Java终止线程

Thread提供了stop()方法终止线程,但是该方法是强行终止,容易产生一些错误,已经被废弃。

可以使用退出标志来终止线程,在run()函数里面设置while循环,把退出标志作为while的条件,当条件为false时,run函数执行完毕,线程就自动终止了。

package com.my_code.thread;

public class MyThread extends Thread {

    public volatile boolean isRunning = true;
   
    public void run(){
        while (isRunning){
            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
   
    public void stopIt(){
        isRunning = false;
    }
   
    public static void main(String[] args) throws InterruptedException{
        MyThread thread = new MyThread();
        thread.start();
        sleep(10000);
        thread.stopIt();
        thread.join();
        System.out.println("线程已经退出!");
    }
   
}

猜你喜欢

转载自www.linuxidc.com/Linux/2016-10/135721.htm