当前位置: 首页 > news >正文

多线程系列二:Thread类

Thread类是jvm用来管理线程的一个类,换句话说,每个线程都有一个唯一的Thread对象与之关联

1.Thread常见构造方法

  1. Thread():创建线程对象
  2. Thread(Runnable target):使用Runnable对象创建线程对象
  3. Thread(String name):创建线程对象,并命名
  4. Thread(Runnable target,String name):使用Runnable对象创建线程对象,并命名
public static void main(String[] args) {Thread t1 = new Thread();Thread t2 = new Thread(new MyRunnable());Thread t3 = new Thread("这是我的名字");Thread t4 = new Thread(new MyRunnable(),"这是我的名字");}

2.Thread的几个常见属性

  1. 属性:ID,获取方法:gteId(),JVM自动分配的身份标识,会保证唯一性
  2. 属性:名称,获取方法:getName()
  3. 属性:状态,获取方法:getState()
  4. 属性:优先级,获取方法:getPriority()
  5. 属性:是否后台线程,获取方法:isDaemon(),要放在start之前使用,括号中设置为true就是后台线程,不设为true就是前台线程,前台线程的运行,会阻止线程结束,后台线程的运行,不会阻止线程结束,咱们代码创建的线程,默认是前台线程,会阻止进程结束,只要前台线程没执行完,进程就不会结合素,即使main已经执行完
  6. 属性:是否存活,获取方法:isAlive(),简单理解就是run方法是否运行结束了,表示内核中的线程是否存在Java代码中定义的线程对象实例,虽然表示一个线程,这个对象本身的生命周期,和内核中的pcb生命周期是完全不同的
  7. 属性:是否被中断,获取方法:isInterrupted()

3.启动一个线程

之前我们看到如果通过重写run方法创建一个线程对象,但线程对象创建出来并不意味着线程就开始运行了
调用start方法,在真的在操作系统底层创建出一个线程
Thread类使用start方法,启动一个线程,对于同一个Thread对象来说,start只能调用一次,要想启动多个线程,就得创建新对象,本质上start会调用系统的api来完成创建线程的操作

面试题:start和run的区别
start和run是不互相干的内容,看起来结果是一样的,但是run没有创建新线程,start是创建一个新的线程,由新线程执行

4.中断一个线程

这个操作非常依赖run内部的代码逻辑,实际上就是让run方法执行完毕
目前常用的有以下两种方式

  • 通过共享的标记来进行沟通
public class demo {public static boolean isQuit = false;public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while(!isQuit){System.out.println("hello thread");try {Thread.sleep(1000);} catch (InterruptedException e) {throw new RuntimeException(e);}}});t.start();Thread.sleep(3000);isQuit = true;}
}

线程何时结束,取决于在另一个线程中何时修改isQuit的值,main线程想要让t线程结束,前提一定是t线程的代码对这样的逻辑有所支持

  • 使用Thread.interrupted()Thread.currentThread().isInterrupted()代替自定义标志位
public class dmeo {public static void main(String[] args) throws InterruptedException {Thread t = new Thread(()->{while(!Thread.currentThread().isInterrupted()){System.out.println("hello thread");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();//注意此处的breakbreak;}}});t.start();Thread.sleep(3000);//修改标志位的值,本质上就是用Thread实例内部自带的标志位代替刚才手动创建的isQuitt.interrupt();}
}

要注意代码中的break,原因:没有sleep,interrupt就可以让线程结束,有sleep就会引起变数,执行sleep过程中,调用interrupt大概率sleep休眠时间还没到,就会被提前唤醒,提前唤醒会做两件事情:1.抛出interruptException异常(被catch捕获)2.清除Thread对象的isInterrupted标志位,通过Interrupt方法,已经在标志位设为true了,但是sleep提前唤醒操作,就把标志位又设回false了,就又继续循环了

sleep清楚标志位,为了给程序员更多的可操作空间,此时我们可以在catch语句中加入代码,做一些处理

  1. 让线程全部结束:break
  2. 不结束,继续执行:不加break
  3. 执行逻辑后再结束:先写代码再加break

5.等待一个线程

影响线程结束的先后顺序
例如使用多个线程并发进行一系列计算,用一个线程阻塞等待上述线程,等到所有线程都计算完了,最终这个线程汇总结果

规则:在哪个线程调用,哪个线程就是等待的一方,使用哪个实例调用,哪个线程就是被等待的一方,什么时候线程运行结束,什么时候join就结束等待

public class ThreadDemo {public static void main(String[] args) throws InterruptedException {Runnable target = ()->{for (int i = 0; i < 3; i++) {System.out.println(Thread.currentThread().getName()+":我还在工作");try {Thread.sleep(1000);} catch (InterruptedException e) {//e.printStackTrace();break;}}System.out.println(Thread.currentThread().getName()+":我结束了");};Thread thread1 = new Thread(target,"李四");Thread thread2 = new Thread(target,"王五");System.out.println("先让李四开始工作");thread1.start();thread1.join();System.out.println("李四工作结束,让王五开始工作");thread2.start();thread2.join();System.out.println("王五工作结束");}
}
  • join还有几个构造方法
  1. public void join():等待线程结束
  2. public void join(long millis):等待线程结束,最多等millis毫秒
  3. public void join(long millis,int nanos):同上,但是是纳秒精度

第一个死等是不科学的,如果在代码中因为死等导致程序卡住,无法继续处理后续逻辑,就是非常严重的bug

6.获取当前线程引用

如果是继承Thread,直接使用this拿到线程实例,如果Runnable或lambda表达式,this就无能为力了,此时this已经不指向Thread对象了,只能用public static Thread currentThreaed()返回当前引用

public class demo2 {public static void main(String[] args) {Thread thread = Thread.currentThread();System.out.println(thread.getName());}
}
输出结果:
mainProcess finished with exit code 0
http://www.xdnf.cn/news/250417.html

相关文章:

  • Window通过虚拟机17安装Ubuntu20.04并安装相关的插件(胎教级教程)
  • 回归树:从原理到Python实战
  • 【C语言】文本操作函数fseek、ftell、rewind
  • 详细介绍Python-pandas-DataFrame全部 功能 函数
  • 存储器层次结构:理解计算机记忆的金字塔
  • 23页PDF | 数据治理实施方案 :规划、执行、评价、改进四步走的管控模式
  • Seata服务端开启事务核心源码解析
  • 位运算题目:寻找重复数
  • 最长公共前缀(14)
  • 基于Koa实现的服务端渲染 ✅
  • 8.进程概念(四)
  • 为什么大模型偏爱Markdown
  • 操作系统(1)多线程
  • 【Machine Learning Q and AI 读书笔记】- 03 小样本学习
  • 数字智慧方案6178丨智慧医院医疗信息化建设之以评促建(61页PPT)(文末有下载方式)
  • 微型计算机串行通信实验三全解析:从原理到实践的探索之旅
  • 《数字图像处理(面向新工科的电工电子信息基础课程系列教材)》章节思维导图
  • 【验证技能】文档要求和好文档注意点
  • Python实现简易博客系统
  • Linux——线程(3)线程同步
  • ✨从噪声到奇迹:扩散模型如何“想象“出世界
  • 本地服务器备份网站数据,本地服务器备份网站的操作步骤
  • 产品手册小程序开发制作方案
  • C++/SDL 进阶游戏开发 —— 双人塔防(代号:村庄保卫战 17)
  • python自动化测试
  • 【业务领域】计算机网络基础知识
  • 基于预计技术研究加速因子:原理、应用场景及模型验证
  • socket-IO复用技术
  • 米酒的功能和优缺点
  • 范围for 和 万能引用