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

完整教程:Java EE初阶启程记03---Thread类及常见方法

 个人主页:寻星探路

作者简介:Java研发方向学习者

个人专栏:、《

⭐️人生格言:没有人生来就会编程,但我生来倔强!!!



目录

1、Thread的常见构造方法

2、Thread的几个常见属性

3、启动一个线程---start()

4、中断一个线程

5、等待一个线程---join()

6、获取当前线程引用

7、休眠当前线程


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

        用我们上面的例子来看,每个执行流,也需要有⼀个对象来描述,类似下图所示,而Thread类的对象就是用来描述一个线程执行流的,JVM会将这些Thread对象组织起来,用于线程调度,线程管理。

1、Thread的常见构造方法

 Thread t1 = new Thread();Thread t2 = new Thread(new MyRunnable());Thread t3 = new Thread("这是我的名字");Thread t4 = new Thread(new MyRunnable(), "这是我的名字");

2、Thread的几个常见属性

        ID是线程的唯一标识,不同线程不会重复

        名称是各种调试工具用到

        状态表示线程当前所处的⼀个情况,下面我们会进一步说明

        优先级高的线程理论上来说更容易被调度到

        关于后台线程,需要记住一点:JVM会在一个进程的所有非后台线程结束后,才会结束运行。

        是否存活,即简单的理解,为run方法是否运行结束了

        线程的中断问题,下面我们进一步说明

public class ThreadDemo {public static void main(String[] args) {Thread thread = new Thread(() -> {for (int i = 0; i < 10; i++) {try {System.out.println(Thread.currentThread().getName() + ": 我还活着");Thread.sleep(1 * 1000);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName() + ": 我即将死去");});System.out.println(Thread.currentThread().getName() + ": ID: " + thread.getId());System.out.println(Thread.currentThread().getName() + ": 名称: " + thread.getName());System.out.println(Thread.currentThread().getName() + ": 状态: " + thread.getState());System.out.println(Thread.currentThread().getName() + ": 优先级: " + thread.getPriority());System.out.println(Thread.currentThread().getName() + ": 后台线程: " + thread.isDaemon());System.out.println(Thread.currentThread().getName() + ": 活着: " + thread.isAlive());System.out.println(Thread.currentThread().getName() + ": 被中断: " + thread.isInterrupted());thread.start();while (thread.isAlive()) {}System.out.println(Thread.currentThread().getName() + ": 状态: " + thread.getState());}}

3、启动一个线程---start()

        之前我们已经看到了如何通过覆写run方法创建⼀个线程对象,但线程对象被创建出来并不意味着线程就开始运行了。

        覆写run方法是提供给线程要做的事情的指令清单

        线程对象可以认为是把李四、王五叫过来了

        而调用start()方法,就是喊⼀声:”行动起来!“,线程才真正独立去执行了。

调用start方法,才真的在操作系统的底层创建出一个线程

4、中断一个线程

        李四⼀旦进到工作状态,他就会按照行动指南上的步骤去进行工作,不完成是不会结束的。但有时我们需要增加⼀些机制,例如老板突然来电话了,说转账的对方是个骗子,需要赶紧停止转账,那张三该如何通知李四停止呢?这就涉及到我们的停止线程的方式了。

目前常见的有以下两种方式:

1)通过共享的标记来进行沟通

2)调用interrupt()方法来通知

示例---1:使用自定义的变量来作为标志位

需要给标志位上加volatile关键字(这个关键字的功能后面介绍)

public class ThreadDemo {private static class MyRunnable implements Runnable {public volatile boolean isQuit = false;@Overridepublic void run() {while (!isQuit) {System.out.println(Thread.currentThread().getName()+ ": 别管我,我忙着转账呢!");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName()+ ": 啊!险些误了⼤事");}}public static void main(String[] args) throws InterruptedException {MyRunnable target = new MyRunnable();Thread thread = new Thread(target, "李四");System.out.println(Thread.currentThread().getName() + ": 让李四开始转账。");thread.start();Thread.sleep(10 * 1000);System.out.println(Thread.currentThread().getName()+ ": ⽼板来电话了,得赶紧通知李四对⽅是个骗⼦!");target.isQuit = true;}
}

示例---2:使用Thread.interrupted()或者Thread.currentThread().isInterrupted()代替自定义标志位

Thread内部包含了一个boolean类型的变量作为线程是否被中断的标记

        使用thread对象的 interrupted() 方法通知线程结束

public class ThreadDemo {private static class MyRunnable implements Runnable {@Overridepublic void run() {// 两种⽅法均可以while (!Thread.interrupted()) {//while (!Thread.currentThread().isInterrupted()) {System.out.println(Thread.currentThread().getName()+ ": 别管我,我忙着转账呢!");try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();System.out.println(Thread.currentThread().getName()+ ": 有内⻤,终⽌交易!");// 注意此处的 breakbreak;}}System.out.println(Thread.currentThread().getName()+ ": 啊!险些误了⼤事");}}public static void main(String[] args) throws InterruptedException {MyRunnable target = new MyRunnable();Thread thread = new Thread(target, "李四");System.out.println(Thread.currentThread().getName()+ ": 让李四开始转账。");thread.start();Thread.sleep(10 * 1000);System.out.println(Thread.currentThread().getName()+ ": ⽼板来电话了,得赶紧通知李四对⽅是个骗⼦!");thread.interrupt();}}

thread收到通知的方式有两种:

1)如果线程因为调用wait/join/sleep等方法而阻塞挂起,则以InterruptedException异常的形式通 知,清除中断标志

        当出现InterruptedException的时候,要不要结束线程取决于catch中代码的写法,可以选择忽 略这个异常,也可以跳出循环结束线程

2)否则,只是内部的一个中断标志被设置,thread可以通过         Thread.currentThread().isInterrupted()判断指定线程的中断标志被设置,不清除中断标志这种方式通知收到的更及时,即使线程正在sleep也可以马上收到。

5、等待一个线程---join()

        有时,我们需要等待一个线程完成它的工作后,才能进行自己的下一步工作。例如,张三只有等李四转账成功,才决定是否存钱,这时我们需要⼀个方法明确等待线程的结束。

public class ThreadDemo {public static void main(String[] args) throws InterruptedException {Runnable target = () -> {for (int i = 0; i < 10; i++) {try {System.out.println(Thread.currentThread().getName() + ": 我还在⼯作!");Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}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注释掉,现象会是怎么样的呢?

6、获取当前线程引用

        这个方法我们已经非常熟悉了

public class ThreadDemo {public static void main(String[] args) {Thread thread = Thread.currentThread();System.out.println(thread.getName());}
}

7、休眠当前线程

        也是我们比较熟悉⼀组方法,有⼀点要记得,因为线程的调度是不可控的,所以,这个方法只能保证实际休眠时间是大于等于参数设置的休眠时间的

 public class ThreadDemo {public static void main(String[] args) throws InterruptedException {System.out.println(System.currentTimeMillis());Thread.sleep(3 * 1000);System.out.println(System.currentTimeMillis());}}
http://www.jsqmd.com/news/7138/

相关文章:

  • 2025 年润滑脂厂家 TOP 企业品牌推荐排行榜,道达尔润滑脂,工业润滑脂,合成润滑脂,高温润滑脂,轴承润滑脂推荐这十家公司!
  • 2025切割机厂家TOP企业品牌推荐排行榜,五轴水刀,大理石水刀,全自动水刀,高压水刀,手持式水刀,高压水刀,大理石水刀,便携式水刀切割机公司推荐!
  • 二十八、API之《System 类》——与框架交互的“桥梁”
  • 二十八、API之《System 类》——与框架交互的“桥梁”
  • 2025橡胶木板材厂家TOP企业品牌推荐排行榜,泰国橡胶木板材,橡胶木免漆板,橡胶木 PET,橡胶木门板,AA 橡胶木,橡胶木指接板公司推荐!
  • 2025润滑油供应商最新权威推荐排行榜:聚焦耐磨润滑油、工业润滑油、鑫美工业润滑油、壳牌润滑油、道达尔润滑油助力企业采购决策
  • 多状态循环泵控件开发
  • 2025活塞杆厂家TOP企业品牌推荐排行榜,精密,不锈钢,调制,超长,油缸,气缸,镀铬,大直径,精细活塞杆推荐这十家公司!
  • 实用指南:WSL2搭建Hadoop伪分布式环境
  • 3整数规划-分支定界法
  • 详细介绍:【计算机视觉】形态学的去噪
  • [apple pencil二代充不上电]
  • 分布式光纤声波振动与AI的深度融合:开启智慧感知新时代 - 指南
  • Flutter完整开发指南 | FlutterDart – The Complete Guide - 教程
  • Flutter实现闲鱼底部导航栏中间突出效果
  • 2025试验机实力厂家品牌公司最新权威推荐榜:精准测试与技术创新标杆之选
  • 完整教程:【JAVA】【BUG】经常出现的典型 bug 及解决办法
  • 读人形机器人28智慧城市2
  • 浅析 AC 自动机
  • VMware ESXi 9.0.1.0 发布 - 领先的裸机 Hypervisor
  • VMware vSphere 9.0.1.0 发布 - 企业级工作负载平台
  • 《索引实战:结构与场景解析》 - 详解
  • 阿里云无影发布首个Agentic Computer形态的个人计算产品 - 详解
  • VMware Cloud Foundation Automation 9.0.1.0 发布 - 私有云自动化平台
  • VMware Cloud Foundation Operations 9.0.1.0 发布 - 私有云运维管理
  • VMware Cloud Foundation Operations for Networks 9.0.1.0 发布 - 云网络监控与分析
  • 2025护栏板厂家TOP企业品牌推荐排行榜,波形护栏板、乡村、公路、道路、镀锌、喷塑、城乡、路侧、两波、三波护栏板推荐这十家公司!
  • 2025 年充电桩厂家TOP企业品牌推荐排行榜,汽车、电车、智能、重卡、电动车直流、新能源车、大功率、一体式双枪、双枪直流、通用快充充电桩公司推荐!
  • 2025加工厂家企业品牌推荐排行榜,走心机、精密细长轴、进口津上机、精密零部件、机械零件非标定制、新能源电机传动轴、紧固件、复杂零件一次成型、内外螺纹台阶轴卡簧槽键槽加工推荐
  • 2025年地磅厂家TOP企业品牌推荐排行榜,电子地磅、物联网、无人值守、汽车衡、防爆、自动称重系统、100 吨地磅、专业地磅汽车衡公司推荐!