zoukankan      html  css  js  c++  java
  • 启动和终止线程

    返回主页面

     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){
                }
            }
        }
        
    }

  • 相关阅读:
    使用 lntelliJ IDEA 创建 Maven 工程的springboot项目
    HTTP协议小记
    TCP/UDP的网络底层实现
    TCP的三次握手和四次挥手
    IP地址和MAC地址绑定的必要性
    什么是回调函数?
    基于TCP实现的Socket通讯详解
    HTTP协议随笔
    计算机虚拟世界的入门常识(1)——信号的原理
    UDP比TCP好用的优势
  • 原文地址:https://www.cnblogs.com/tianzhiyun/p/9557423.html
Copyright © 2011-2022 走看看