java线程停止代码 java线程如何停止

如何停止java线程有三种方法可以使终止线程 。
1.使用退出标志,使线程正常退出,也就是当run方法完成后线程终止 。
2.使用stop方法强行终止线程(这个方法不建议使用,因为stop和suspend、resume一样 , 也可能发生不可预料的结果) 。
3.使用interrupt方法中断线程 。
至于以上三种方法 的具体代码网上可以查找 。
java中终止线程的方法?在Java的多线程编程中 , java.lang.Thread类型包含了一些列的方法start(),stop(),stop(Throwable)andsuspend(),destroy()andresume() 。通过这些方法,我们可以对线程进行方便的操作,但是这些方法中,只有start()方法得到了保留 。本文是海文国际小编搜索整理的关于JAVA中终止线程的方法,供参考复习,希望对大家有所帮助!
如果真的需要终止一个线程 , 可以使用以下几种方法:
1、让线程的run()方法执行完,线程自然结束 。(这种方法最好)
2、通过轮询和共享标志位的方法来结束线程,例如while(flag){},flag的初始值设为真 , 当需要结束时,java课程培训机构建议将flag的值设为false 。(这种方法也不很好,因为如果while(flag){}方法阻塞了 , 则flag会失效)
如何终止java线程关闭线程有几种方法,
【java线程停止代码 java线程如何停止】一种是调用它里面的stop()方法
另一种就是你自己设置一个停止线程的标记 (推荐这种)
代码如下:
package com.demo;
//测试Thread的stop方法和自己编写一个停止标记来停止线程;
public class StopThread implements Runnable{
//停止线程的标记值boolean;
private boolean flag = true;
public void stopThread(){
flag = false;
}
public void run(){
int i=0;
while(flag){
i;
System.out.println(Thread.currentThread().getName() ":" i);
try{
Thread.sleep(1000);
}catch(Exception e){
}
System.out.println(Thread.currentThread().getName() "==" i);
}
}
public static void main(String args[]){
StopThread st = new StopThread();
Thread th = new Thread(st);
Thread th1 = new Thread(st);
th.start();
th1.start();
try{
Thread.sleep(5500);
}catch(Exception e){
}
/*
如果使用Thread.stop方法停止线程,不能保证这个线程是否完整的运行完成一次
run方法;但是如果使用停止的标记位,那么可以保正在真正停止之前完整的运行完
成一次run方法;
*/
th.stop();
st.stopThread();
}
}
Java如何中断一个正在运行的线程 程序是很简易的 然而 在编程人员面前 多线程呈现出了一组新的难题 如果没有被恰当的解决 将导致意外的行为以及细微的 难以发现的错误
在本篇文章中 java线程停止代码我们针对这些难题之一 如何中断一个正在运行的线程
背景中断(Interrupt)一个线程意味着在该线程完成任务之前停止其正在进行的一切 有效地中止其当前的操作 线程是死亡 还是等待新的任务或是继续运行至下一步 就取决于这个程序 虽然初次看来它可能显得简单 但是 java线程停止代码你必须进行一些预警以实现期望的结果 java线程停止代码你最好还是牢记以下的几点告诫
首先 忘掉Thread stop方法 虽然它确实停止了一个正在运行的线程 然而 这种方法是不安全也是不受提倡的 这意味着 在未来的JAVA版本中 它将不复存在
一些轻率的家伙可能被另一种方法Thread interrupt所迷惑 尽管 其名称似乎在暗示著什么 然而 这种方法并不会中断一个正在运行的线程(待会将进一步说明) 正如Listing A中描述的那样 它创建了一个线程 并且试图使用Thread interrupt方法停止该线程 Thread sleep()方法的调用 为线程的初始化和中止提供了充裕的时间 线程本身并不参与任何有用的操作
class Example extends Thread {boolean stop=false;public static void main( String args[] ) throws Exception {Example thread = new Example ();System out println( Starting thread );thread start();Thread sleep( );System out println( Interrupting thread );thread interrupt();Thread sleep( );System out println( Stopping application );//System exit( );}public void run() {while(!stop){System out println( Thread is running );long time = System currentTimeMillis();while((System currentTimeMillis() time)) {}}System out println( Thread exiting under request );}}
如果你运行了Listing A中的代码 你将在控制台看到以下输出
Starting thread Thread is running Thread is running Thread is running Interrupting thread Thread is running Thread is running Thread is running Stopping application Thread is running Thread is running Thread is running
甚至 在Thread interrupt()被调用后 线程仍然继续运行
真正地中断一个线程
中断线程最好的 最受推荐的方式是 使用共享变量(shared variable)发出信号 告诉线程必须停止正在运行的任务 线程必须周期性的核查这一变量(尤其在冗余操作期间) 然后有秩序地中止任务 Listing B描述了这一方式
Listing Bclass Exampleextends Thread {volatile boolean stop = false;public static void main( String args[] ) throws Exception {Examplethread = new Example ();System out println(Starting thread);thread start();Thread sleep();System out println(Asking thread to stop);thread stop = true;Thread sleep();System out println(Stopping application);//System exit();}public void run() {while ( !stop ) {System out println(Thread is running);long time = System currentTimeMillis();while ( (System currentTimeMillis() time)(!stop) ) {}}System out println(Thread exiting under request);}}
运行Listing B中的代码将产生如下输出(注意线程是如何有秩序的退出的)
Starting thread Thread is running Thread is running Thread is running Asking thread to stop Thread exiting under request Stopping application
虽然该方法要求一些编码 但并不难实现 同时 它给予线程机会进行必要的清理工作 这在任何一个多线程应用程序中都是绝对需要的 请确认将共享变量定义成volatile 类型或将对它的一切访问封入同步的块/方法(synchronized blocks/methods)中
到目前为止一切顺利!但是 当线程等待某些事件发生而被阻塞 又会发生什么java线程停止代码?当然 如果线程被阻塞 它便不能核查共享变量 也就不能停止 这在许多情况下会发生 例如调用Object wait() ServerSocket accept()和DatagramSocket receive()时 这里仅举出一些
他们都可能永久的阻塞线程 即使发生超时 在超时期满之前持续等待也是不可行和不适当的 所以 要使用某种机制使得线程更早地退出被阻塞的状态
很不幸运 不存在这样一种机制对所有的情况都适用 但是 根据情况不同却可以使用特定的技术 在下面的环节 我将解答一下最普遍的例子
使用Thread interrupt()中断线程
正如Listing A中所描述的 Thread interrupt()方法不会中断一个正在运行的线程 这一方法实际上完成的是 在线程受到阻塞时抛出一个中断信号 这样线程就得以退出阻塞的状态 更确切的说 如果线程被Object wait Thread join和 Thread sleep三种方法之一阻塞 那么 它将接收到一个中断异常(InterruptedException) 从而提早地终结被阻塞状态
因此 如果线程被上述几种方法阻塞 正确的停止线程方式是设置共享变量 并调用interrupt()(注意变量应该先设置) 如果线程没有被阻塞 这时调用interrupt()将不起作用 否则 线程就将得到异常(该线程必须事先预备好处理此状况) 接着逃离阻塞状态 在任何一种情况中 最后线程都将检查共享变量然后再停止 Listing C这个示例描述了该技术
Listing Cclass Exampleextends Thread {volatile boolean stop = false;public static void main( String args[] ) throws Exception {Examplethread = new Example ();System out println(Starting thread);thread start();Thread sleep();System out println(Asking thread to stop);thread stop = true;//如果线程阻塞 将不会检查此变量thread interrupt();Thread sleep();System out println(Stopping application);//System exit();}public void run() {while ( !stop ) {System out println(Thread running);try {Thread sleep();} catch ( InterruptedException e ) {System out println(Thread interrupted);}}System out println(Thread exiting under request);}}
一旦Listing C中的Thread interrupt()被调用 线程便收到一个异常 于是逃离了阻塞状态并确定应该停止 运行以上代码将得到下面的输出
Starting thread Thread running Thread running Thread running Asking thread to stop Thread interrupted Thread exiting under request Stopping application
中断I/O操作
然而 如果线程在I/O操作进行时被阻塞 又会如何?I/O操作可以阻塞线程一段相当长的时间 特别是牵扯到网络应用时 例如 服务器可能需要等待一个请求(request) 又或者 一个网络应用程序可能要等待远端主机的响应
如果你正使用通道(channels)(这是在Java 中引入的新的I/O API) 那么被阻塞的线程将收到一个 ClosedByInterruptException异常 如果情况是这样 其代码的逻辑和第三个例子中的是一样的 只是异常不同而已
但是 你可能正使用Java 之前就存在的传统的I/O 而且要求更多的工作 既然这样 Thread interrupt()将不起作用 因为线程将不会退出被阻塞状态 Listing D描述了这一行为 尽管interrupt()被调用 线程也不会退出被阻塞状态
Listing Dimport java io *;class Exampleextends Thread {public static void main( String args[] ) throws Exception {Examplethread = new Example ();System out println(Starting thread);thread start();Thread sleep();System out println(Interrupting thread);thread interrupt();Thread sleep();System out println(Stopping application);//System exit();}public void run() {ServerSocket socket;try {socket = new ServerSocket( );} catch ( IOException e ) {System out println(Could not create the socket);return;}while ( true ) {System out println(Waiting for connection);try {Socket sock = socket accept();} catch ( IOException e ) {System out println(accept() failed or interrupted);}}}}
很幸运 Java平台为这种情形提供了一项解决方案 即调用阻塞该线程的套接字的close()方法 在这种情形下 如果线程被I/O操作阻塞 该线程将接收到一个SocketException异常 这与使用interrupt()方法引起一个InterruptedException异常被抛出非常相似
唯一要说明的是 必须存在socket的引用(reference) 只有这样close()方法才能被调用 这意味着socket对象必须被共享 Listing E描述了这一情形 运行逻辑和以前的示例是相同的
Listing Eimport*;import java io *;class Exampleextends Thread {volatile boolean stop = false;volatile ServerSocket socket;public static void main( String args[] ) throws Exception {Examplethread = new Example ();System out println(Starting thread);thread start();Thread sleep();System out println(Asking thread to stop);thread stop = true;thread socket close();Thread sleep();System out println(Stopping application);//System exit();}public void run() {try {socket = new ServerSocket( );} catch ( IOException e ) {System out println(Could not create the socket);return;}while ( !stop ) {System out println(Waiting for connection);try {Socket sock = socket accept();} catch ( IOException e ) {System out println(accept() failed or interrupted);}}System out println(Thread exiting under request);}}
以下是运行Listing E中代码后的输出
Starting thread Waiting for connection Asking thread to stop accept() failed or interrupted Thread exiting under request Stopping application
多线程是一个强大的工具 然而它正呈现出一系列难题 其中之一是如何中断一个正在运行的线程 如果恰当地实现 使用上述技术中断线程将比使用Java平台上已经提供的内嵌操作更为简单 lishixinzhi/Article/program/Java/gj/201311/27481
java线程如何停止?通过调用interrupt方法可以使得处于阻塞状态的线程抛出一个异常,即interrupt方法可以用来中断一个正处于阻塞状态的线程;另外 , 改方法还会设置线程的中断状态(注:isInterrupted()可以用来查询中断状态) 。
线程阻塞在reader.readLine()时,即使主线程改变了标志变量,但是并不能立即结束子线程,只有等待阻塞被打破,且运行到下一次循环条件判断的时候才能终止 。所以在使用这种方法时,应该考虑到阻塞这种情况 。当然 , 如果整个循环内的操作属于同一事务时,这种方法倒很不错 。
调用线程对象的interrupt()时,sleep的线程会抛出InterruptedException异常 , 从而中断循环,终止线程 。但是如果是IO如输入这些阻塞,中断的方法又不起作用了,还有就是对于没有阻塞的线程,调用interrupt()是达不到终止线程的效果的 。
关于java线程停止代码和java线程如何停止的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息 , 记得收藏关注本站 。

    推荐阅读