当前位置:网站首页>[multithreading] is there only one way to implement threads or four ways
[multithreading] is there only one way to implement threads or four ways
2022-07-22 14:33:00 【Juzijun who doesn't want to sleep】
Implement a thread , I'm learning Java When , The way I heard the teacher speak , There are three kinds of , Inherit Thread, Realization Runnable, Realization Callable. Some articles on the Internet say there are four , One more thread pool . Others say that only 1 Kind of . So I'm a little interested in exploring how threads are implemented .
1, Inherit Thread
The first way to implement threads is , Inherit Thread class , And rewrite run Method .
There is nothing to say about this kind of .
2, Realization Runnable Interface
The second method , Find a class , Realization Runnable Interface , rewrite run Method , And an instance of this implementation class , Throw it new Thread() In the constructor of .
It can be seen from it that , This approach still depends on new Thread() To create threads , Realized Runnable Interface MyRunnable Not even start Method .MyRunnable It just participates as a parameter of the constructor Thread Construction .
So this MyRunnable What did you do .
Click all the way down and you will find clues here You can see , Actually MyRunnable As new Thread() Role of parameters , Will be Runnable The interface is assigned to target, Specify this Thread What tasks to run .
in other words , Realization Runnable, In essence, it's just new Thread
3, Realization Callable
The third method , Realization Callable Interface , And rewrite call Method .Callable And Runnable Is the difference between the Callable There is a return value , And may throw exceptions . and Runnable no return value .
And Runnable Different ,Runnable no return value , Therefore, it can be used synchronously ,start It won't block after , You can go on start Next thread or do something else .Callable Because of the return value , If you continue to use synchronization , It will block before returning the result , If you need to establish multiple threads at this time , Then you have to wait for the thread execution to end one by one . Now computers are multi-core cpu, Support multi-threaded simultaneous operation . therefore Callable Constant and asynchronous Future Use a combination of . The demonstration here is also combined Future demonstrate (FutureTask yes Tuture Interface implementation ).
You can see , Actually Future It is also used as a parameter to participate in the construction Thread, And constructors and Runnable That's the same one . because Future Realized RunnableFuture Interface , and RunnableFuture Interface inherited Runnable Interface and Feature Interface . let me put it another way ,Future Realized Runnable Interface .
Runnable The method has already mentioned ,Runnable structure Thread In fact, by giving Thread Medium Runnable target Variable assignment , Tell thread run How to do . And in the FutureTask in , Rewrote RunnableFuture Of run Method , its run In the method , Would call call Method , That is, the previous implementation Callable Interface when rewriting the thread to do specific tasks call Method .
public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable<V> c = callable;
// In the structure FutureTask when state Set as NEW
if (c != null && state == NEW) {
V result;
boolean ran;
try {
// Execute here call Method
result = c.call();
ran = true;
} catch (Throwable ex) {
result = null;
ran = false;
setException(ex);
}
if (ran)
set(result);
}
} finally {
// runner must be non-null until state is settled to
// prevent concurrent calls to run()
runner = null;
// state must be re-read after nulling runner to prevent
// leaked interrupts
int s = state;
if (s >= INTERRUPTING)
handlePossibleCancellationInterrupt(s);
}
}
In this way, it is connected , In fact, it's still through new Thread, Appoint Runnable The reference of the implementation class of is target, Appoint run Method . and FutureTask Of run It's called call Method . So we can say , This method is actually through new Thread To build threads .
4, Thread pool
Thread pool is relatively simple . We know , Thread pool itself is not a way to create threads , It just manages the created threads . In essence, we need to rely on the first three ways to implement threads . Therefore, it is not the way to implement threads .
summary
From the above we can see that , The way to really create threads , Essentially only new Thread() A kind of . But show it in a different way , Different new Thread There are three ways , ordinary new Thread, Realization Runnable, Realization Callable. Thread pools are not included , Thread pool is just for managing threads , The threads created in the first three ways will be handed over to you for use and recycling , Creating threads still depends on the first three methods .
边栏推荐
- [ERR] 1273 - Unknown collation: ‘utf8mb4_ 0900_ ai_ ci‘
- State owned enterprises work overtime in 996, but job hopping offers are outsourcing. What should we do?
- [development of large e-commerce projects] thread pool - completable future -48
- 微波雷达传感器模块,智能感知人体存在,实时感应交互控制应用
- 3. ZABBIX installation
- Typescript array extension use
- 【服务器数据恢复】华为某型号服务器raid6数据恢复案例
- Adaptive length input box
- Ardunio development - steering gear control
- 【多线程】创建线程池有几种方式
猜你喜欢
MFC obtains cfindreplacedialog control messages by registering window information
Parker hydraulic oil pump pv140r1k1t1nmm1
Rexroth Rexroth plunger pump a15vso
Redis data structure analysis (I)
Time complexity and complexity
51 MCU peripherals: LED dot matrix
国企加班996,跳槽offer却又是外包,该怎么办?
STM32状态机编程实例——全自动洗衣机(上)
parker液压油泵PV140R1K1T1NMM1
It can be said to be the best right-click menu management tool so far
随机推荐
The way of practicing and fighting strange things: detailed explanation of sym in ES6
cookie和seesion的区别和联系
BOM operation - jog animation
AI robot era in the eyes of Ubisoft Technology
面试遇到的问题
暑期沉淀web学习——SQL注入(布尔盲注&时间盲注)
Master slave replication of MySQL Cluster (I)
rexroth比例阀4WRPEH6C3B04L-3X/M/24F1-885
Summer precipitation Web Learning - SQL injection (Boolean blind injection & time blind injection)
MFC obtains cfindreplacedialog control messages by registering window information
The development of raspberry pie - the Internet cable connects raspberry pie and laptop directly - records the bitter process
STM32状态机编程实例——全自动洗衣机(上)
二叉树递归进阶【下】
Go language go command line tool
迟迟不发业绩预告,京东方此时无声胜有声?
SOC第一个工程
Helm --set usage examples and basic usage commands sorting
State owned enterprises work overtime in 996, but job hopping offers are outsourcing. What should we do?
Full link voltage test: the dispute between shadow database and shadow table
Prometheus prometheus+grafana, monitoring setup and basic interface configuration