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...");
        }
    }
    

      

  • 相关阅读:
    自定义分页二
    CheckBox实现跨页面多选
    正试图在 os 加载程序锁内执行托管代码。不要尝试在 DllMain 或映像初始化函数内运行托管代码,这样做会导致应用程序挂起。
    DropDownList下拉框多选
    通用查询
    AutoCAD自动加载DLL文件的方法
    软件开发(团队管理)
    正确地做事与做正确的事
    C#.NET实现邮件的发送
    多附件的上传
  • 原文地址:https://www.cnblogs.com/lnas01/p/7896169.html
Copyright © 2011-2022 走看看