码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA并发实现二(线程中止)

时间:2016-05-03 00:17:14      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

JAVA并发实现二(线程中止)

标签:

原文地址:http://www.cnblogs.com/xiaotao726/p/5453488.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!