当前位置:网站首页>Thread 类的基本用法——一网打尽
Thread 类的基本用法——一网打尽
2022-07-31 06:27:00 【是小鱼儿哈】
目录
一、线程的创建
1、继承Thread类,重写run方法
方式一、不借助匿名内部类
- 创建一个继承于Thread类的子类
- 在该子类中重写Thread类中的run方法
- 实例化该子类类型,用父类Thread引用重写了run方法的子类对象,向上转型
- 通过上述引用调用start方法,创建该线程,并将该线程(PCB参与到系统调度中,与其他线程一起进行随机调度执行)

方式二、借助匿名内部类
- 借助该匿名内部类将上述三步:子类继承Thread、重写run、创建实例化对象,合并为一步
- 调用start方法


2、实现 Runnable, 重写 run方法
方式一:不用匿名内部类
- 1.创建一个实现了Runnable接口的类
2.用该类去实现Runnable中的抽象方法:run()
3.创建实现类的对象
4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5.通过Thread类的对象调用start()

方式二、借助匿名内部类
- 把创建一个实现了Runnable接口的类、重写run方法、实例化该类合并
- 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象(这一步还可以与上面的合并)
- 调用start()方法

3、使用 lambda 表达式


二、线程中断
1、使用自己的标志位来区分线程是否要结束


2、使用Thread自带的标志位

那么从上面我们可以看到,因为在t线程中调用了sleep方法,使得抛出了异常——在这里我们的程序成功的捕获了该异常,进入了catch语句,打印了异常信息;
那么我们可不可以通过改变catch语句中的内容来对该线程进行不同的处理呢?当然可以!!!

代码栗子
public class thread {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("线程正在运行中...");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// e.printStackTrace();打印异常信息
//break; 1、立即退出
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
break; // 2、稍后退出
// 不退出,捕获到异常后什么也不干,相当于的忽略了该异常
}
}
});
System.out.println("线程开始运行");
t.start();
Thread.sleep(3000);
System.out.println("控制该线程退出!");
t.interrupt();
}
}总结
三、线程等待
先来看一个栗子

从这我们可以看到因为在t1、t2start之后,t1、t2和主线程的执行顺序是由操作系统进行随机调度的,那么我们怎样才能让t1、t2线程都执行完了,主线程再记录结束的时间戳呢?
通过join方法!!!
通过join方法我们可以让main线程主动的等待(想让谁阻塞,就再谁的线程里调用join)


四、线程休眠
sheep能够让线程休眠一会!!!

实例

五、获取线程实例

栗子一
栗子二
栗子三
边栏推荐
猜你喜欢

【Go语言刷题篇】Go完结篇函数、结构体、接口、错误入门学习

简单谈谈Feign

How to set the computer password?How to add "safety lock" to your computer

基金投顾业务

2022.07.24_每日一题

2022.07.20_每日一题

解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie

超级详细的mysql数据库安装指南

Analysis of the principle and implementation of waterfall flow layout

基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
随机推荐
interrupt and pendSV
nohup原理
Kubernetes scheduling
ros小乌龟画图
DAY18: Xss Range Clearance Manual
2022.07.20_每日一题
手把手教你开发微信小程序自定义底部导航栏
Bulk free text translation
leetcode 406. Queue Reconstruction by Height 根据身高重建队列(中等)
Zotero | Zotero translator plugin update | Solve the problem that Baidu academic literature cannot be obtained
Titanic 预测问题
Yu Mr Series 】 【 2022 July 022 - Go Go teaching course of container in the dictionary
Zabbix6.2 Surprise Release!Especially optimize the performance of medium and large environment deployment!
DirectExchange switch simple introduction demo
2022.7.29 Array
04-SDRAM: Read Operation (Burst)
2022.07.12 _ a day
电压源的电路分析知识分享
我开发了一个利用 Bun 执行 .ts / .js 文件的 VS Code 插件
解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie