启动和终止线程

返回主页面

 https://blog.csdn.net/xu__cg/article/details/52831127

 

理解中断

中断可以理解为线程的一个标识位属性,它表示一个运行中的线程是否被其他线程进行了中断操作(通过调用该线程的interrupt()进行操作)。

运行中的线程自身通过检查是否被中断进行响应,

1.线程通过isInterrupted()来进行判断是否被中断

2.线程调用静态方法Thread.interrupted()对当前线程的中断标识位进行复位。

如果该线程处于终结状态,即使该线程被中断过,在调用该线程对象的isInterrupted()时依旧为返回false.

 

许多声明抛出InterruptedException的方法(例如 Thread.sleep(long millis)方法)这些方法抛出InterruptedException之前,java虚拟机会先将该线程的中断标示位清除,然后抛出interruptedException,此时调用isInterrupted()方法将会返回false.

 

package com.qdb.thinkv.thread.base;

import java.util.concurrent.TimeUnit;

import com.qdb.thinkv.thread.utils.SleepUtils;

public class Interrupted {
    
    public static void main(String[] args) throws Exception {
        //Sleep不停的尝试睡眠
        Thread sleepThread=new Thread(new SleepRunner(),"SleepRunner");
        sleepThread.setDaemon(true);
        //Busy不停的运行
        Thread busyThread=new Thread(new BusyRunner(),"BusyRunner");
        busyThread.setDaemon(true);
        
        sleepThread.start();
        busyThread.start();
        
        //休眠5秒
        TimeUnit.SECONDS.sleep(5);
        sleepThread.interrupt();
        busyThread.interrupt();
        
        System.out.println("SleepThread interrupted is "+sleepThread.isInterrupted());
        System.out.println("BusyThread interrupted is "+busyThread.isInterrupted());
        
        SleepUtils.second(2);
    }
    
    static class SleepRunner implements    Runnable {
        public void run() {
            while(true){
                SleepUtils.second(10);
            }
        }
    }
    
    static class BusyRunner implements    Runnable {
        public void run() {
            while(true){
            }
        }
    }
    
}

 

posted @ 2018-08-29 22:37  yunchong1019  阅读(304)  评论(0编辑  收藏  举报