java线程interrupt用法_Java线程中interrupt那点事 | 学步园

1.先看一下例子程序:

import java.io.IOException;

import java.net.ServerSocket;

import javax.rmi.CORBA.Tie;

/*

*@author: ZhengHaibo

*web: http://blog.csdn.net/nuptboyzhb

*mail: zhb931706659@126.com

*2014-3-16 Nanjing,njupt,China

*/

public class TestThread {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Thread t1=new Thread(){

@Override

public void run(){

try {

int i=0;

while (i++<100000000){

//nothing

}

System.out.println("A1");

} catch (Exception e) {

// TODO: handle exception

System.out.println("B1");

}

}

};

t1.start();

t1.interrupt();//无法中断正在运行的线程

try {

t1.join();

} catch (InterruptedException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

Thread t2=new Thread(){

@Override

public void run(){

try {

Thread.sleep(5000);

System.out.println("A2");

} catch (Exception e) {

// TODO: handle exception

System.out.println("B2 "+e.toString());

}

}

};

t2.start();

t2.interrupt();//可以中断正在休眠的线程,并抛出异常

try {

t2.join();

} catch (InterruptedException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

Thread t3=new Thread(){

@Override

public void run(){

try {

this.wait(5000);

System.out.println("A3");

} catch (Exception e) {

// TODO: handle exception

System.out.println("B3 "+e.toString());

}

}

};

t3.start();

t3.interrupt();

try {

t3.join();

} catch (InterruptedException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

Thread t4=new Thread(){

@Override

public void run(){

try {

synchronized (this) {

this.wait(5000);

}

System.out.println("A4");

} catch (Exception e) {

// TODO: handle exception

System.out.println("B4 "+e.toString());

}

}

};

t4.start();

t4.interrupt();

try {

t4.join();

} catch (InterruptedException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

try {

final ServerSocket serverSocket=new ServerSocket(8080);

Thread t5=new Thread(){

@Override

public void run(){

try {

serverSocket.accept();

System.out.println("A5");

} catch (Exception e) {

// TODO: handle exception

System.out.println("B5 "+e.toString());

}

}

};

t5.start();

t5.interrupt();//无法中断

t5.stop();//线程停止

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

try {

t4.start();

System.out.println("A6");

} catch (Exception e) {

// TODO: handle exception

System.out.println("B6 "+ e.toString());

}

}

}

运行结果为:

A1

B2 java.lang.InterruptedException: sleep interrupted

B3 java.lang.IllegalMonitorStateException

B4 java.lang.InterruptedException

B6 java.lang.IllegalThreadStateException

附录1:sleep和wait的区别

1、这两个方法来自不同的类分别是,sleep来自Thread类,和wait来自Object类。

sleep是Thread的静态类方法,谁调用的谁去睡觉,即使在a线程里调用了b的sleep方法,实际上还是a去睡觉,要让b线程睡觉要在b的代码中调用sleep。

2、最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法。

sleep不出让系统资源;wait是进入线程等待池等待,出让系统资源,其他线程可以占用CPU。一般wait不会加时间限制,因为如果wait线程的运行资源不够,再出来也没用,要等待其他线程调用notify/notifyAll唤醒等待池中的所有线程,才会进入就绪队列等待OS分配系统资源。sleep(milliseconds)可以用时间指定使它自动唤醒过来,如果时间不到只能调用interrupt()强行打断。

Thread.Sleep(0)的作用是“触发操作系统立刻重新进行一次CPU竞争”。

3、使用范围:wait,notify和notifyAll只能在同步控制方法或者同步控制块里面使用,而sleep可以在任何地方使用    synchronized(x){       x.notify()      //或者wait()    }

4、sleep必须捕获异常,而wait,notify和notifyAll不需要捕获异常

相关博客:

java并发编程相关博客:

更多阅读:

[3].Java并发性和多线程介绍目录http://ifeve.com/java-concurrency-thread-directory/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/453554.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Kotlin Native新增Objective-C互操作能力以及对WebAssembly的支持

根据JetBrains技术主管Nikolay Igotti的介绍&#xff0c;Kotlin/Native 0.4已经可用于为iOS和macOS开发原生应用。此外该版本还为WebAssembly平台提供了实验性支持。 \\Kotlin/Native对iOS/macOS开发的支持&#xff0c;关键在于实现了与Objective-C的互操作性。JetBrains目前已…

TranslateAnimation动画

众所周知&#xff0c;TranslateAnimation是android中重要的一个动画函数&#xff0c;很多时候我们都需要使用它来实现更好的UI效果&#xff0c;今天就简单研究下这个TranslateAnimation。TranslateAnimation这个位移动画主要有三个构造函数&#xff0c;对应着三种不同的参数形式…

maven项目使用jacoco插件检测代码覆盖率详细配置

使用maven构建项目&#xff08;java项目或者web项目都可以&#xff09; jacoco插件的配置参考官方网址&#xff1a;http://www.eclemma.org/jacoco/trunk/doc/maven.html &#xff08;1&#xff09;配置jacoco的依赖jar包 <dependency><groupId>org.jacoco</gro…

JAVA如何取得空list成员类型_String 类型的List作为一个成员变量保存,保存成功后取对象时报空指针...

异常&#xff1a;Caused by: java.lang.NullPointerException at org.litepal.crud.DataHandler.setToModelByReflection(DataHandler.java:1341) at org.litepal.crud.DataHandler.setGenericValueToModel(DataHandler.java:787) at org.litepal.crud.DataHandler.query(DataH…

C语言:几种字符输入函数的区别

几种字符输入函数的区别&#xff1a; 1、getche()函数:用于从键盘读入一个字符并显示&#xff0c;然后直接执行下一条语 句。2、getch()函数:用于从键盘中读入一个字符&#xff0c;但不显示在屏幕上&#xff0c;然后执行下一条语句。3、getchar()函数&#xff1a;用于从键盘读…

VCG Mesh刚性旋转(变换矩阵)

文章目录 一、简介二、实现代码三、实现效果参考资料一、简介 旋转矩阵如果从线性空间的角度来看,它类似于一个投影过程。假设坐标 P ( x 1 , y 1 , z 1 ) P(x_1,y_1,z_1)

薪水增长多少,新机会才值得考虑?

薪水增长多少,新机会才值得考虑? 阴历年马上就要来到&#xff0c;猪年正在向我们招手。相信有些朋友年后考虑新的要作机会&#xff0c;年终奖和第13个薪水已到手&#xff0c;是考虑一下离开这个让自己不“爽”公司的时候了&#xff0c;哈哈&#xff01; 但是&#xff0c;薪水…

ScaleAnimation动画

ScaleAnimation动画是用来进行缩放的动画&#xff0c;我在使用时刚开始有些不解的问题后来经过学习&#xff0c;有了一个更深的了解。先来看看源码&#xff0c;其实ScaleAnimation有四个构造函数&#xff0c;这里我只列出了其中的一个&#xff0c;因为另外的三个其实都只是这个…

Swift快速入门(一)第一个Swift程序

1. 本系列说明 本系列只是一个Swift快速入门的教程&#xff0c;并没有详尽的介绍Swift&#xff0c;Swift也并不是一个简单的编程语言&#xff0c;所以要想详尽的系统的学习Swift&#xff0c;本系列并不适合你&#xff0c;此系列只是让开发者可以快速的用Swift来进行开发。另外学…

java 判断数字变化增减_java String 强化操作 判断数字 字符串转阿拉伯数字,相似度等等...

importjava.io.BufferedReader;importjava.io.StringReader;importjava.util.ArrayList;importjava.util.List;importjava.util.regex.Matcher;importjava.util.regex.Pattern;/***author*/public classStrings {/*** 全角转半角**paramsbc 全角字符*returnString*/public stat…

[CareerCup] 4.7 Lowest Common Ancestor of a Binary Search Tree 二叉树的最小共同父节点

4.7 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree. LeetCode上的原题&#xff0c;请参见我之前的博客Lo…

让猎头雨天送伞--大话猎头

让猎头雨天送伞--大话猎头(1) Arthur毕业之后&#xff0c;在一同家公司的研发部工作了7年&#xff0c;从初级开发工程师一直做到项目经理&#xff0c;过手十几个大项目&#xff0c;现在带领8人的研发团队。猎头最近频频与他沟通&#xff0c;希望他考虑几个外企研发主管的机会…

android布局的一些知识

(一)android:layout_alignParentBottom 控制该组件是否与布局容器底端对齐android:layout_alignParentLeft 控制该组件是否与布局容器左边对齐android:layout_alignParentRight 控制该组件是否与布局容器右边对齐android:layout_alignParentTop 控制该组件是否与布局容器顶端对…

IE8兼容问题总结---trim()方法

1.IE8不支持,jquery的trim()去空格的方法 错误表现 : 会报错,对象不支持此属性或方法; 解决办法 : 使用正则匹配空格 例如 : /^\s|\s$/greplace(/^\s|\s$/g,"");转载于:https://www.cnblogs.com/lizhiwei8/p/8392589.html

java的流套接_java-使用流关闭套接字

我的以下问题非常简单.这是我的代码&#xff1a;public class Protocol implements Runnable {private SSLSocket socket null;private InputStream is null;private OutputStream os null;...public Protocol(Socket s) {socket (SSLSocket)s;is socket.getInputStream()…

简历撰写

没什么可写的项目&#xff0c;或者自己说不太清&#xff0c;效果也不明显的项目&#xff0c;就不要写简历上了转载于:https://www.cnblogs.com/brainstorm/p/7942669.html

如何真正做好项目管理?

项目要能顺利执行其实并不简单&#xff0c;如果又渉及多个单位合作&#xff0c;困难程度又大增。 从项目经理的工作日志片段&#xff0c;可以看出每个项目经理应该都有自已悲惨的故事&#xff0c;程度恐怕只有过之而无不及。项目经理到底应该有那些看家本领呢&#xff1f; …

日历视图的XML属性

日历视图的XML属性 : -- 设置样式 : android:dateTextAppearance, 设置日期文字显示样式; -- 设置首日 : android:firstDayOfWeek, 设置星期几是每周的第一天, 默认是周一; -- 选中颜色 : android:focusedMonthDateColor, 设置选中日期所在月份日期颜色; -- 最大日期 : android…

作业30-首页列表显示全部问答,完成问答详情页布局

首页列表显示全部问答&#xff1a;将数据库查询结果传递到前端页面 Question.query.all()前端页面循环显示整个列表。问答排序app.route(/) def index():context{questions:Question.order_by(creat_time).query.all()}return render_template("index.html",**contex…

java重置radiobutton的选项_求助:这道题显示radiobutton男女的功能和重置功能怎么做...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼package org.demo.app.gui; import java.awt.BorderLayout;import java.awt.Color;import java.awt.Container;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax…