当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA中 终止线程的方法介绍

JAVA中 终止线程的方法介绍

2019年07月22日  | 移动技术网IT编程  | 我要评论
在java的多线程编程中,java.lang.thread类型包含了一些列的方法start(), stop(), stop(throwable) and suspend()

在java的多线程编程中,java.lang.thread类型包含了一些列的方法start(), stop(), stop(throwable) and suspend(), destroy() and resume()。通过这些方法,我们可以对线程进行方便的操作,但是这些方法中,只有start()方法得到了保留。

在sun公司的一篇文章《why are thread.stop, thread.suspend and thread.resume deprecated? 》中详细讲解了舍弃这些方法的原因。

如果真的需要终止一个线程,可以使用以下几种方法:
1、让线程的run()方法执行完,线程自然结束。(这种方法最好)


2、通过轮询和共享标志位的方法来结束线程,例如while(flag){},flag的初始值设为真,当需要结束时,将flag的值设为false。(这种方法也不很好,因为如果while(flag){}方法阻塞了,则flag会失效)


复制代码 代码如下:

public class somethread implements runnable {

private volatile boolean stop = false;

public void terminate() {

stop = ture;

}

public void run() {

while(stop) {

// ... some statements

}

}

}


 

如果线程因为执行sleep()或是wait()而进入not runnable状态,假如是wait() 用标志位就方法就不行了,

public final void wait(long timeout)
                throws interruptedexception此方法导致当前线程(称之为 t)将其自身放置在对象的等待集中,然后放弃此对象上的所有同步要求。即当前线程变为等待状态

wait() 的标准使用方法

synchronized(obj){

while(<不满足条件>){

obj.wait();

}

满足条件的处理过程

}

而您想要停止它,您可以使用第三种即

3 使用interrupt(),而程式会丢出interruptedexception例外,因而使得执行绪离开run()方法,

例如:

 

复制代码 代码如下:

public class somethread {

public static void main(string[] args)

{

thread thread=new thread(new runnable(){

 

public void run() {

 while (!thread.interrupted()) {
                // 处理所要处理的工作
                try {
                   

system.out.println("go to sleep");

thread.sleep(1000);
                } catch (interruptedexception e) {
                    e.printstacktrace();
               

system.out.println("i am interrupted!");
                }

});

thread.start();

thread.interrupt();

}

}


执行结果为:

go to sleep

i am interrupted!

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网