当前位置:网站首页>Multithreading basics (concept, create, interrupt)
Multithreading basics (concept, create, interrupt)
2022-07-30 07:41:00 【HDLaZy】
1:什么是线程,and process distinctions
线程:线程就是一个执行流,The code is executed sequentially between each thread,Multiple copies of code can be executed simultaneously between multiple threads.
为什么需要线程(线程优势):
- Threads can be fully utilizedCPU资源,提高执行效率.
- 等待IOother operations can be performed during the time.
- Threads are more lightweight than processes,Resource consumption is less than process.
thread disadvantage:增加编码复杂度,Thread safety concerns need to be considered.
线程状态:
- NEW:创建态
- RUNNABLE:可运行态(Contains ready and running states)The program cannot determine the ready state or the running state
- WAITING:等待
- TIMED_WAITING:超时等待
- BLOCKED:阻塞
- TERMINATED:销毁
线程的实现方式:
- 内核线程:JavaMultithreading is a lightweight implementation of kernel threads(相比进程,是一种轻量级进程,创建,调度,Destruction efficiency is high)
- 用户线程:implemented by the program,Including thread state transfer,调度等
面试题:线程和进程
- Processes are memory independent,相互隔离,Multiple threads of a process share memory.
- 进程是分配资源的最小单位,而线程是CPU调度执行的最小单位.
- 相比进程,线程的创建,The cost of destruction is small,执行效率高.
- Processes run independently,Errors between threads can cause the entire process to crash.
2:线程的创建,中断
面试题:线程创建的方式
继承Thread类
class MyThread extends Thread{ @Override public void run() { System.out.println("这是继承Thread的实现方式"); } }实现Runnable接口
Thread thread=new Thread(new Runnable() { @Override public void run() { System.out.println("这是实现Runnable接口的实现方式"); } });实现Callable接口
FutureTask<Object> futureTask=new FutureTask<>(new Callable<Object>() { @Override public Object call() throws Exception { return "这是实现Callable借助于FutureTask的实现方式"; } }); Thread thread=new Thread(futureTask); thread.start(); //获取返回值 System.out.println(futureTask.get());
面试题:start()和run()方法
使用Start()方法会创建线程,而使用Run()方法仅仅是在main线程中执行Run()方法的调用,instead of creating new threads.StartThe way to start the thread,Run()属于线程任务的描述.
| 方法 | 说明 |
|---|---|
| getId() | 获取线程ID |
| getName() | 获取线程名 |
| getState() | 获取线程状态 |
| getPriority() | 获取线程优先级 |
| isDaemon() | 是否为后台线程 |
| isAlive() | 是否存活 |
| join() | 等待线程死亡 |
| Thread.currentThread() | 获取当前线程的引用 |
| sleep(long millis) | Pauses the currently executing thread for the specified number of milliseconds |
后台线程:JavaAt least one non-background thread in the process is alive,The process will not end.(Background threads are threads that are self-started for program startup)
线程中断API:
什么是线程中断:线程运行的过程中,Interrupted by other threads,But whether to end or continue execution is determined by the logic code of the target thread itself.
模拟线程中断----Custom thread interrupt flag:
The custom thread interrupt flag cannot be interrupted 处于阻塞/等待/超时等待状态 的线程
public class Custom flag interrupts {
//Whether to interrupt the flag bit
private static boolean flag=false;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
//当标志位为trueThen exit the loop,线程执行结束
for(int i=0 ;i <10 && !flag; i ++){
System.out.println("打印:"+i);
try {
//In order to make the thread execute slower, it is ensured that the change of the interrupt flag bit can be sensed before the execution is completed
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
//为了让mainThread execution is a bit slower,能够让threadAfter the thread executes for a period of time, the operation of changing the interrupt flag bit is performed
Thread.sleep(5);
//mainThe thread modifies the interrupt flag bit
flag=true;
}
}
| 线程中断API | 说明 |
|---|---|
| interrupt() | Modify the thread interrupt flag totrue |
| interrupted() | Returns the current interrupt flag bit,And the reset flag is false |
| isInterrupted() | Returns the current interrupt flag bit |
利用中断APIProcess thread is interrupted:
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
//isInterrupted()Get the interrupt flag bit without resetting it
for(int i=0;i<100 && !Thread.currentThread().isInterrupted();i++){
System.out.println("打印"+i);
}
}
});
thread.start();
Thread.sleep(1);
//修改中断标志位
thread.interrupt();
}
If let the target threadSleep(),while sleeping,When the interrupt signal arrives, it will be thrownInterruptedException异常,And after throwing an exception,The target thread continues execution until completion.(Because when thrownInterruptedException异常后,The process flags are reset)
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10 && !Thread.currentThread().isInterrupted();i++){
System.out.println("打印"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
Thread.sleep(3000);
thread.interrupt();
}
使用interrupt()The thread is not necessarily interrupted after the method:
interrupt()方法并不是中断线程,Just modify the interrupt flag bit,More like a notification,Notify the target thread of interruption,However, whether to interrupt depends on the logic code of the target thread.
public static void main(String[] args) throws InterruptedException {
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
//将上述代码 !Thread.currentThread().isInterrupted()去掉
//Even if the interrupt signal is received at this time,The target thread is still executed
for(int i=0;i<100 ;i++){
System.out.println("打印"+i);
}
}
});
thread.start();
Thread.sleep(1);
//修改中断标志位
thread.interrupt();
}
边栏推荐
猜你喜欢
随机推荐
力扣题解7.27
测试开发工程师成长日记018 - 测试面试必备题记录(持续更新)
二、1稀疏sparsearray数组
GAIA-IR:GraphScope 上的并行化图查询引擎
Unity Shader 标准光照模型
Mastering JESD204B (3) – Debugging of AD6676
02-Cycript的使用
memset()函数的使用总结和细节
元宇宙与图扑国风的碰撞,科技与文化的虚实融合
Desthiobiotin-PEG4-Acid|脱硫生物素-PEG4-酸| 供应商和制造商
瀑布流(自定义布局实现)
从安装到编译: 10分钟教你在本地使用和开发GraphScope
libgrape-lite on GPUs:GPU助力加速图分析任务
测试开发工程师成长日记010 - Jenkins中的CI/CD/CT(持续集成构建/持续交付/持续测试)
测试第二题
Event Delivery and Responder Chains
MongoDB-介绍,数据类型,基本语句
图扑软件数字孪生民航飞联网,构建智慧民航新业态
牛顿迭代法求方程的根
掌握JESD204B(二)–AD6676的调试









