停止线程的两种方法
来源:互联网 发布:什么是网络安全意识 编辑:程序博客网 时间:2024/06/05 23:44
使用stop()方法停止线程会造成一些请理性的工作的不到完成,也可能造成数据的不完整,一般我们使用异常法或者使用退出标致return来停止线程。
①异常法
package com.test;import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;public class YeildTest extends Thread{@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();try {for(int i=500000;i>0;i--){if(interrupted()) {System.out.println("线程已经终止。。。。。。。。。退出");throw new InterruptedException();}System.out.println(i);}} catch (InterruptedException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}}public static void main(String[] args) {YeildTest yt = new YeildTest();yt.setPriority(10);yt.start();try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}yt.interrupt();try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("停止线程。。。。。");}}结果:
...............
499463
线程已经终止。。。。。。。。。退出
java.lang.InterruptedException
at com.test.YeildTest.run(YeildTest.java:15)
停止线程。。。。。
②退出标致(return)结束线程
package com.test;import org.omg.PortableInterceptor.SYSTEM_EXCEPTION;public class YeildTest extends Thread{@Overridepublic void run() {// TODO Auto-generated method stubsuper.run();for(int i=500000;i>0;i--){if(interrupted()) {System.out.println("线程已经终止。。。。。。。。。退出");return;}System.out.println(i);}}public static void main(String[] args) {YeildTest yt = new YeildTest();yt.setPriority(10);yt.start();try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}yt.interrupt();try {Thread.sleep(10);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("停止线程。。。。。");}}
结果:
..........
499435
线程已经终止。。。。。。。。。退出
停止线程。。。。。
0 0
- 停止线程的两种方法
- 使Java线程停止的两种方法
- Java判断线程是否是停止状态的两种方法
- 停止线程的三种方法
- 停止线程的两种方式(异常和Return)
- 线程的两种方法
- java停止线程的方法
- java 线程停止的方法
- Java线程停止的方法
- 停止线程的三个方法
- Qt停止线程的方法
- Java线程停止的方法
- 停止线程的多种方法
- ant 脚本里面启动、停止tomcat的两种方法
- 线程的停止、守护线程、join()方法
- Java停止一个线程的几种方法
- android 停止 终止 Thread 线程的三种方法
- 线程的两种基本的方法
- 百度搜索可以视同广告吗?
- 一幅图大致了解Android与javaEE的关系
- ST_LINK/V2 SWIM和SWD、JTAG下载口说明
- 郑帅师兄的五年博士总结
- 使用百度地图的总结
- 停止线程的两种方法
- hdu 5059 Help him(模拟)
- iOS安全–实时查看模拟器的日志输出
- nova compute报kvm权限问题
- Lyp
- Android---引导界面的制作
- mac os 连阿里云之windows server2008
- Android xml预览布局时,超出屏幕怎么看效果
- [Sencha ExtJS & Touch] singletap 和 tap的区别