当前位置:   article > 正文

java关闭线程

java 关闭线程

1.使用状态位关闭正在运行的线程

  1. class MyThread implements Runnable
  2. {
  3. private volatile boolean stop = false; //定义为volatile类型,避免使用缓存
  4. public void setStop(boolean stop)
  5. {
  6. this.stop = stop;
  7. }
  8. public void run()
  9. {
  10. while (!stop)
  11. {
  12. System.out.println(Thread.currentThread().getName() + " is running");
  13. }
  14. System.out.println(Thread.currentThread().getName() + " is finished");
  15. }
  16. }

        测试:

  1. public class test {
  2. public static void main(String[] args) throws InterruptedException{
  3. MyThread mythread = new MyThread();
  4. Thread thread = new Thread(mythread);
  5. thread.start();
  6. Thread.sleep(1000);
  7. mythread.setStop(true);
  8. }
  9. }
        结果为:

  1. Thread-0 is running
  2. Thread-0 is running
  3. Thread-0 is running
  4. Thread-0 is running
  5. Thread-0 is finished
        使用这种方式需要注意每次循环都要判断状态


2.使用interrupt()关闭休眠阻塞线程

               当线程等待某事件发生而被阻塞,此时是否能够使用状态标记呢?答案是否定的,因为线程被阻塞,那么他根本就得不到执行,也就不能检查状态变量,也就不能停止。  这种情况下可以使用interrupt()方法。

               interrupt()只是把线程的状态改为中断状态,但是interrupt()方法只对执行了sleep()、wait()、join()方法而休眠的线程,使他们不再休眠,同时会抛出InterruptException异常

  1. class MyThread implements Runnable
  2. {
  3. public void run()
  4. {
  5. try
  6. {
  7. Thread.sleep(10000);
  8. }
  9. catch (InterruptedException e)
  10. {
  11. System.out.println("已经被中断了");
  12. }
  13. System.out.println(Thread.currentThread().getName() + " is finished");
  14. }
  15. }
             测试:

  1. public class test {
  2. public static void main(String[] args) throws InterruptedException{
  3. MyThread mythread = new MyThread();
  4. Thread thread = new Thread(mythread);
  5. thread.start();
  6. Thread.sleep(1000);
  7. thread.interrupt();
  8. }
  9. }
              结果:

  1. 已经被中断了
  2. Thread-0 is finished

              中断之后会抛出异常,在catch中可以进行其他处理


3.关闭IO阻塞线程

               对于io阻塞线程,java都会提供相应的关闭阻塞的办法。例如,一个网路应用程序可能要等待远端主机的相应,这个时候可以使用套接字close来关闭

  1. class MyThread extends Thread
  2. {
  3. private ServerSocket server = null;
  4. public void stopThread()
  5. {
  6. try
  7. {
  8. if (server != null)
  9. {
  10. server.close();
  11. System.out.println("成功关闭");
  12. }
  13. }
  14. catch (IOException e)
  15. {
  16. System.out.println("关闭出现异常");
  17. }
  18. }
  19. public void run()
  20. {
  21. try
  22. {
  23. server = new ServerSocket(3333);
  24. }
  25. catch (IOException e)
  26. {
  27. e.printStackTrace();
  28. }
  29. }
  30. }
               测试:

  1. public class test {
  2. public static void main(String[] args) throws InterruptedException{
  3. MyThread mythread = new MyThread();
  4. mythread.start();
  5. Thread.sleep(300);
  6. mythread.stopThread();
  7. }
  8. }
            结果为:

成功关闭

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/1004186
推荐阅读
相关标签
  

闽ICP备14008679号