zoukankan      html  css  js  c++  java
  • 【多线程学习笔记整理】002_线程的停止、暂停、与yield

    一、停止线程的三种方式

      停止线程是多线程中的一个很重要的点,停止线程意味着在线程处理完当前任务之前终止正在做的操作,但是如果不能正确的操作,可能会发生不可预期的结果。

      1)使用退出标志,使线程正常退出,也就是当run方法完成后线程终止;

      2)使用Thread.stop()方法强行终止线程,但是不推荐这种方法,因为stop和suspend以及resume方法一样,都是作废过期的方法,使用它们可能会产生不可预料的结果;

      3)使用interrupt方法。

    二、使用interrupt方法

      举两个栗子:

      栗子一

       

      栗子二

        

      抛异常方式终止线程:举个栗子

      public class StopThread2 extends Thread {
          /*
          public void run() {
              for (int i = 0; i < 200000; i++){
                  if(this.interrupted()){
                      System.out.println("当前线程已经中断,循环即将退出");
                      break;
                  }
                  System.out.println(i);
              }
              //通过break方式不行,break只能终止循环,不能终止线程,还是抛异常吧
              System.out.println("for循环虽然终止了,我还在运行");
          }
          */
          @Override
          public void run() {
              try {
                  for (int i = 0; i < 200000; i++){
                      if(this.interrupted()){
                          System.out.println("当前线程已经中断");
                          throw new InterruptedException();
                      }
                      System.out.println(i);
                  }
              } catch (InterruptedException e) {
                  System.out.println("进入catch块,线程即将退出");
                  e.printStackTrace();
              }
          }
    }

     三、线程的暂停

      线程的暂停方法为suspend(),线程的恢复方法为resume(),来看看api上的说明

      

        这两个方法已经被弃用,所以我们不做过多解释。

     四、yield()方法

        yield()方法是Thread类的静态方法,作用是放弃当前的CPU资源,将它让给其他任务去占用CPU执行时间,但是这个‘其他任务’并不确定,有可能刚刚放弃,然后马上又获得CPU时间片

       举个栗子:  

      public class YieldThread extends Thread {
          @Override
          public void run() {
              super.run();
              long startTime = System.currentTimeMillis();
              for(int i = 0; i < 500000; i++){
                  //测试有无yield()方法的时候的耗时
                  //Thread.yield();
                  i++;
              }
              long endTime = System.currentTimeMillis();
              System.out.println("耗时:" + (endTime - startTime) + "毫秒");
          }
      }
      
      public class TestClass {
          public static void main(String[] args) {
              Thread thread = new YieldThread();
              thread.start();
          }
      }
      
      运行结果:
          无yield方法:耗时:3毫秒
          有yield方法:耗时:145毫秒

        

  • 相关阅读:
    mysql数据库安装,启动和关闭
    python学习笔记(xlsxwriter模块使用)
    redis集群搭建
    gpasswd 命令详解
    linux CPU使用率过高或负载过高的处理思路
    Django模型(ORM)
    Django模板层(template)
    Windows下安装node.js(npm) git+vue
    Sublime Text 3:3114的安装(目前最新),插件emmet的安装
    opacity在IE6~8下无效果,解决的办法
  • 原文地址:https://www.cnblogs.com/carryLess/p/9680642.html
Copyright © 2011-2022 走看看