zoukankan      html  css  js  c++  java
  • Interrupt、Interrupted、IsInterrupted

    1、interrupt() 
    interrupt方法用于中断线程。调用该方法的线程的状态为将被置为"中断"状态。
    注意:线程中断仅仅是置线程的中断状态位,不会停止线程。需要用户自己去监视线程的状态为并做处理。
     
    2、interrupted() 和 isInterrupted()
     
    private native boolean isInterrupted( boolean ClearInterrupted);
    

      

    public static boolean interrupted () {
      //清除标记位
    return currentThread().isInterrupted(true); }
    public boolean isInterrupted () {
      //不清除标记位直接返回
    return isInterrupted(false); } 

    如果这个参数为true,说明返回线程的状态位后,要清掉原来的状态位(恢复成原来情况)。

    class Example2 extends Thread {
        public static void main(String args[]) throws Exception {
            Example2 thread = new Example2();
            System.out.println("Starting thread...");
            thread.start();
            Thread.sleep(3000);
            System.out.println("Asking thread to stop...");
            // 发出中断请求
            thread.interrupt();
            Thread.sleep(3000);
            System.out.println("Stopping application...");
        }
    
        public void run() {
            // 每隔一秒检测是否设置了中断标示
            while (!Thread.currentThread().isInterrupted()) {
                System.out.println("Thread is running...");
                long time = System.currentTimeMillis();
                // 使用while循环模拟 sleep
                while ((System.currentTimeMillis() - time < 1000) ) {
                }
           /*
           try{sleep(1000);}catch(InterruptException e){e.printStackTrace();}
           */
            }
            System.out.println("Thread exiting under request...");
        }
    }
    

      

  • 相关阅读:
    3D 立体动态图 代码:
    自由切换 网页上的 ico 图标
    ES6 基本语法:
    JavaScript中class类的介绍
    React_01_ECMAScript6
    使用JS计算前一天和后一天
    Web 前端学习计划
    read
    java对象实例化
    关于为什么java需要垃圾回收
  • 原文地址:https://www.cnblogs.com/lnas01/p/7896169.html
Copyright © 2011-2022 走看看