zoukankan      html  css  js  c++  java
  • JAVA并发实现二(线程中止)

    package com.subject01;
    
    public class InterruptDemo {
    
        public static void main(String[] args) {
            SimpleThread st = new SimpleThread();
            Thread t = new Thread(st);
            t.start();
            try {  
                Thread.sleep(2000);   
            }catch(InterruptedException e){  
                e.printStackTrace();  
            }  
            System.out.println("in main() - interrupting other thread");  
            //中断线程t  
            // 如果只是单纯的调用interrupt,线程并没有真正的终止,可搭配return进行使用
            t.interrupt();  
            System.out.println("in main() - leaving");  
            
            System.out.println("================================");
            System.out.println("测试isInterrupt:");
            testIsinterrupt();
        }
        
        public static void testIsinterrupt(){
            
            Thread t = Thread.currentThread();
            // isInterrupted() 判断线程是否被中止,如果被中止则返回true,否则则范围false ;
            System.out.println("A当前线程是否被中止:"+t.isInterrupted());
            t.interrupt();
            System.out.println("B当前线程是否被中止:"+t.isInterrupted());
            // 如果Thread.sleep()抛出异常,则会清除中止标识
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                System.out.println("C当前线程是否被中止:"+t.isInterrupted());
            }
            System.out.println("D当前线程是否被中止:"+t.isInterrupted());
            
        }
    
    }
    class SimpleThread implements Runnable{
    
        @Override
        public void run() {
            try {
                System.out.println("in run() - about to sleep for 20 seconds");  
                Thread.sleep(20000);  
                System.out.println("in run() - woke up");
            } catch (InterruptedException e) {
                System.out.println("in run() - interrupted while sleeping");  
                //如果没有return,线程不会实际被中断,它会继续打印下面的信息  
                return ;
            }  
            System.out.println("in run() - leaving normally");  
        }
    
    }

    http://blog.csdn.net/ns_code/article/details/17091267

  • 相关阅读:
    leetcode练习:26. Remove Duplicates from Sorted Array
    leetcode练习:11. Container With Most Water
    leetcode练习:5. Longest Palindromic Substring
    leetcode练习:2.Add Two Numbers
    算法笔记:分治
    (排序回顾)快速排序
    (排序回顾)归并排序
    leetcode练习:2017/09/21~09/22
    算法笔记:递归&迭代
    在Treeview中节点的data属性中保存记录类型及其消除的办法
  • 原文地址:https://www.cnblogs.com/xiaotao726/p/5453488.html
Copyright © 2011-2022 走看看