Thread 线程关闭

2019-11-22  本文已影响0人  散枫

1.Thread线程

2.结束Thread线程的几种方法

3.使用退出标志终止线程

public class ThreadSafe extends Thread {
    public volatile boolean exit = false;
        public void run() {
        while (!exit){
            //do something
        }
    }
}

/**
 * stop thread running
 */
public void stop() {
    if (exit ) {
        exit = false;
    }
}
定义了一个退出标志exit,当exit为true时,while循环退出,exit的默认值为false.在定义exit时,使用了一个Java关键字volatile,这个关键字的目的是使exit同步,也就是说在同一时刻只能由一个线程来修改exit的值

4.使用interrupt()方法终止线程

public class ThreadSafe extends Thread {
    public void run() {
        while (true){
            try{
                 Thread.sleep(5*1000);阻塞5妙
            }catch(InterruptedException e){
                 e.printStackTrace();
                 break;//捕获到异常之后,执行break跳出循环。
            }
        }
    }
}

public class ThreadSafe extends Thread {
    public void run() {
        while (!isInterrupted()){
            //do something, but no tthrow InterruptedException
        }
    }
}

public class ThreadSafe extends Thread {
    public void run() {
        while (!isInterrupted()){ //非阻塞过程中通过判断中断标志来退出
            try{
                Thread.sleep(5*1000);//阻塞过程捕获中断异常来退出
            }catch(InterruptedException e){
                e.printStackTrace();
                break;//捕获到异常之后,执行break跳出循环。
            }
        }
    }
}

5.使用stop方法终止线程

上一篇下一篇

猜你喜欢

热点阅读