首页 技术 正文
技术 2022年11月21日
0 收藏 753 点赞 3,423 浏览 1508 个字

一、停止线程的三种方式

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

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

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

  3)使用interrupt方法。

二、使用interrupt方法

  举两个栗子:

  栗子一

   【多线程学习笔记整理】002_线程的停止、暂停、与yield

  栗子二

    【多线程学习笔记整理】002_线程的停止、暂停、与yield

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

  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上的说明

  【多线程学习笔记整理】002_线程的停止、暂停、与yield

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

四、yield()方法

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

   举个栗子:  

  public class YieldThread extends Thread {
   @Override
  public void run() {
   super.run();
   long startTime = System.currentTimeMillis();
   for(int i = ; i < ; 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毫秒

    

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,031
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,520
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,368
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,148
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,781
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,860