停止线程的两种方法

来源:互联网 发布:什么是网络安全意识 编辑:程序博客网 时间: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