当前位置:网站首页>Tencent interview -- please design a thread pool to implement sequential execution
Tencent interview -- please design a thread pool to implement sequential execution
2022-07-28 15:28:00 【evanYang_】
List of articles
background
Xiaobian is happy , Shit, shit ExecutorService executor = Executors.newSingleThreadExecutor(); The scheme of single thread has been explained ; By the way, post the code .
SingleThreadExecutor Realization
package com.evan.springboot.study;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author evanYang
* @version 1.0
* @date 2020/5/26 In the morning 10:41
*/
public class ExecutorDemos {
public static void main(String[] args) {
Thread a = new Thread(){
@Override
public void run() {
System.out.println("thread a perform ");
try {
Thread.sleep(200);
System.out.println(" perform ing.....");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread b = new Thread(){
@Override
public void run() {
System.out.println("thread b perform ");
try {
Thread.sleep(200);
System.out.println(" perform ing.....");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread c = new Thread(){
@Override
public void run() {
System.out.println("thread c perform ");
System.out.println(" perform ing.....");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(a);
executor.execute(b);
executor.execute(c);
executor.shutdown();
}
}

We can see that it is executed in sequence ; I'm very happy to have wood ;
interviewer : This is a single thread execution ? There are wood and others better idea Well ?
I wonder if my friends have better ideas
Based on semaphores (Semaphore) Realization
Lock and synchronized Is the mutual exclusion of locks , If a thread locks a resource , Then other threads can only wait for the release of resources . That is, only one thread executes at a time , Until this thread finishes executing or unlock. and Semaphore It can control the access of multiple threads to each resource at the same time .Semaphore The function is similar to that of toilet 5 Pit , If there is 10 Individuals need to go to the bathroom , How many people can only go to the bathroom at the same time ?
At the same time, there can only be 5 Individuals can occupy , When any of the five people get out of the way , The other thing waiting for is 5 One more person can occupy
. Other waiting 5 Individuals can get priority opportunities at random , You can also get opportunities in the order of first come, first served , It depends on the construction Semaphore Parameter options passed in when object . Of course, a single semaphore Semaphore Object can realize the function of mutex , And the lock can be obtained by a thread , Then another thread releases the lock , This is used in some situations of deadlock recovery .Semaphores are used for multithreading multitasking multitasking synchronization , When a thread completes an action, it tells other threads through semaphore , Other threads are doing something . in other words Semaphore It is not necessarily to lock a resource , It's a concept of process . Let's say there is A,B Two threads ,B The operation of the thread may have to wait A Execute after the thread finishes executing , This task
It doesn't have to be locking a resource , It can also perform some calculations or data processing , They may not access shared variables , It's just a logical sequence .java Count the semaphore (Semaphore) Maintaining a license set . call acquire() Get a license ,release() Release a license . stay java in , You can also set whether the semaphore adopts fair mode , If executed in a fair manner , Then the threads will be in the order of (FIFO) perform , If it is unfair , Then it is possible that the post request is at the head of the queue .
Semaphore It is currently used in a multithreaded environment , The semaphore of the operating system is a very important concept , It is used in process control .java Concurrent Libraries Semaphore It's easy to control the semaphore ,Semaphore You can control the number of resources that can be accessed at the same time .
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
final Semaphore semaphore = new Semaphore(5);
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"Accessing:" + NO);
Thread.sleep((long) (Math.random() * 10000));
semaphore.release();
System.out.println("------------------" + semaphore.availablePermits());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
executorService.execute(runnable);
}
executorService.shutdown();
}

边栏推荐
- [leetcode] binary search given an N-element ordered (ascending) integer array num and a target value target, write a function to search the target in num. if the target value exists, return the subscr
- .net core 2.2 版本跨域配置
- DJ-131/60C电压继电器
- ERROR:bokeh.core.validation.check:E-1001 (BAD_COLUMN_NAME)
- 配置cx-oracle 解决(cx_Oracle.DatabaseError) DPI-1047: Cannot locate a 64-bit Oracle Client library: “Th
- PMP每日一练 | 考试不迷路-7.28(包含敏捷+多选)
- crmeb pro2.2即将增加的功能都有哪些?
- The difference between @notnull, @notblank, @notempty of commonly used verification annotations
- Collation of MySQL error prone knowledge points (to be updated)
- DAY:7/11
猜你喜欢

Multi merchant mall system with relatively clean code

Jogy-61 voltage relay

Deepfacelab model parameters collection

JOGY-61电压继电器

Jy-7ga/1 voltage relay

HJS-DE1/2时间继电器

汇编学习
Data synchronization of new version

Classic Dijkstra and the longest way

Crmeb Standard Edition window+phpstudy8 installation tutorial (II)
随机推荐
Stack expression
Crmeb Standard Edition window+phpstudy8 installation tutorial (II)
sql 开发篇一 之 表锁查询及解锁
shellcode编写学习-环境
Gfpgan blurred photo repair artifact
Solve the problem of pycharm using PowerShell
Back compilation failed
.net core 2.2 版本跨域配置
Svg verification code recognition experience
20、通道分配任务实现
Installing CONDA and configuring Jupiter
svg 验证码识别体验
MIT指出公开预训练模型不能乱用
chrome插件调试
How Charles installs and uses
Ry-d1/1 voltage relay
Slider restore and validation (legal database)
Have you ever used the single merchant mall, which is smooth enough to make people feel numb?
新版数据同步问题
volatile原理