好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java结束线程的三种方法及该如何选择

java常用的结束一个运行中的线程的方法有3中:使用退出标志,使用interrupt方法,使用stop方法。

1.使用退出标志

即在线程内部定义一个bool变量来判断是否结束当前的线程:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

public class ThreadSafe extends Thread {

  public volatile boolean exit = false ;

  public void run() {

   while (!exit){

    //do work

   }

  }

 

  public static void main(String[] args) throws Exception {

   ThreadFlag thread = new ThreadFlag();

   thread.start();

   sleep( 5000 ); // 主线程延迟5秒

   thread.exit = true ; // 终止线程thread

   thread.join();

   System.out.println( "线程退出!" );

  }

}

这种情况一般是将线程的任务放在run方法中的一个while循环中,而由这个bool变量来对while循环进行控制。

2.使用interrupt方法

这种方法需要判断当前的线程所处于的状态:
(1)当前线程处于阻塞状态时
线程处于阻塞状态一般是在使用了 sleep,同步锁的 wait,socket 中的 receiver,accept 等方法时,会使线程处于阻塞状态。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public class ThreadInterrupt extends Thread {

  public void run() {

   try {

    sleep( 50000 ); // 延迟50秒

   }

   catch (InterruptedException e) {

    System.out.println(e.getMessage());

   }

  }

  public static void main(String[] args) throws Exception {

   Thread thread = new ThreadInterrupt();

   thread.start();

   System.out.println( "在50秒之内按任意键中断线程!" );

   System.in.read();

   thread.interrupt();

   thread.join();

   System.out.println( "线程已经退出!" );

  }

}

注意这种情况写,使用 interrupt 方法结束线程的时候,一定要先捕获 InterruptedException 异常之后通过 break 来跳出循环,才能正常结束 run 方法。

(2)线程未处于阻塞状态时

使用 isInterrupted() 判断线程的中断标志来退出循环。当使用 interrupt() 方法时,中断标志就会置 true,和使用自定义的标志来控制循环是一样的道理。

?

1

2

3

4

5

6

7

8

9

10

11

12

public class ThreadSafe extends Thread {

  public void run() {

   while (!isInterrupted()) { //非阻塞过程中通过判断中断标志来退出

    try {

     Thread.sleep( 5 * 1000 ); //阻塞过程捕获中断异常来退出

    } catch (InterruptedException e) {

     e.printStackTrace();

     break ; //捕获到异常之后,执行 break 跳出循环

    }

   }

  }

}

3.使用stop方法来结束线程

?

1

2

3

4

5

6

7

8

9

public class Main {

  public static void main(String[] args) throws InterruptedException {

   MyThread myThread = new MyThread();

   myThread.start();

   Thread.sleep( 3000 ); // 间隔3秒后

   myThread.stop();  // 结束线程

   System.out.println( "结束了" );

  }

}

4.结束方法的选择

建议使用标志位和interrupt方法来结束线程,stop方法已经不建议再被使用了。
因为采用 stop 是不安全的,主要影响点如下:

thread.stop() 调用之后,创建子线程的线程就会抛出 ThreadDeatherror 的错误; 调用 stop 会释放子线程所持有的所有锁。导致了该线程所持有的所有锁的突然释放(不可控制),那么被保护数据就有可能呈现不一致性。

以上就是Java结束线程的三种方法及该如何选择的详细内容,更多关于Java 结束线程的资料请关注其它相关文章!

原文链接:https://segmentfault测试数据/a/1190000039696074

查看更多关于Java结束线程的三种方法及该如何选择的详细内容...

  阅读:16次