JAVA并发实现二(线程中止)
2016-05-02 23:17
477 查看
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并发实现一(并发的实现之Thread和Runnable的区别)
- jdk动态代理
- java MVC模式
- Struts2架构思想、配置文件
- java的Scanner,char等基础知识!
- Java8新特性Stream API与Lambda表达式详解(2)
- java设计模式(工厂模式)
- freemarker 用template快速构造XML
- JAVA语言之基数排序
- String abc=null;String abc="";String abc;三种写法有什么区别?
- 【GOF23设计模式】_工厂模式JAVA229-231
- Windows10 SpringMVC中需要使用setPath()才能保证cookie保存成功
- Spring3.1集成Quartz,让你的任务执行随心所欲
- Java线程池——FutureTask
- struts2入门到精通教程
- 适配器模式
- Java之Volatile关键字使用
- JSON格式数据解析(Java版)
- java连接mysql时用到的参数
- Java学习(十)