当前位置:网站首页>How to create threads
How to create threads
2022-07-18 05:01:00 【Notes sharing and perception of programming Xiaobai】
How to create threads
Method 1 , Use it directly Thread
// The argument to the constructor is to assign a name to the thread , recommend
Thread t1 = new Thread("t1") {
@Override
// run Method implements the task to be executed
public void run() {
log.debug("hello");
}
};
t1.start();
Method 2 , Use Runnable coordination Thread
hold 【 Threads 】 and 【 Mission 】( Code to execute ) Separate
- Thread On behalf of thread
- Runnable Runnable tasks ( The code to be executed by the thread
// Create task object
Runnable task2 = new Runnable() {
@Override
public void run() {
log.debug("hello");
}
};
// Parameters 1 It's the object of the mission ; Parameters 2 It's the thread name , recommend
Thread t2 = new Thread(task2, "t2");
t2.start();
Method 3 ,Callable
Runnable One function of the interface is , When the thread terminates ( namely run() When finished ), We can't make the thread return results . To support secondary functions ,Java Provides Callable Interface .
- In order to achieve Runnable, You need to realize that you don't regret anything run() Method , And for Callable Interface , You need to return the result on completion Call() Method
- call() Method can throw an exception , and run() no way
- In order to achieve Callable It has to be rewritten call Method
Threadl Constructors in classes cannot be passed Callable Of , It can only be transmitted Runnable
So it is wrong to create threads in this way :
new Thread(new Callable(),"tt").start()
Thread Can only
```java
new Thread(new Runnable(),"tt").start()

Then you must find a class , Make it both Runnable It matters , And also Callable It matters ,,,FeatureTask,FeatureTask yes Runnable Implementation class , At the same time, its constructor can transmit Callable, That's it Callable And Runnable The associated .
1、Callable And Runnable The difference between
1)Callable The prescribed method is call(),Runnable The prescribed method is run().
(2)Callable After the task is executed, it can return the value , and Runnable The task of cannot return a value
(3)call Methods can throw exceptions ,run Method can not
(4) function Callable The mission can get a Future object ,Future Represents the result of an asynchronous calculation
2、Callable combination futureTask Create execution tasks , Pass the task to Thread in , Then start the execution of the task
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTaskTest = new FutureTask(new Callable() {
@Override
public Integer call() throws Exception {
System.out.println("callable1");
return 1024;
}
});
FutureTask futureTask = new FutureTask(()->{
System.out.println("callable2");
return 2048;
});
new Thread(futureTask,"t1").start();
while (!futureTask.isDone()){
System.out.println(" adopt isDone You can judge whether the task is over ");
}
System.out.println(" adopt get Method can obtain the execution result of the task ");
System.out.println(futureTask.get());
}
}
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt isDone You can judge whether the task is over
adopt get Method can obtain the execution result of the task
2048
3**、FutureTask The details of the :**
- get Method location , It's usually on the last line , Otherwise, the main thread will block in get Wait for it to return
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(()->{
System.out.println("callable2");
Thread.sleep(10000);
return 2048;
});
System.out.println(" Task start :"+ System.currentTimeMillis());
new Thread(futureTask,"t1").start();
System.out.println(futureTask.get());
System.out.println("main Thread end :"+ System.currentTimeMillis());
}
}
Task start :1657859321584
callable2
2048
main Thread end :1657859331587
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(()->{
System.out.println("callable2");
Thread.sleep(10000);
return 2048;
});
System.out.println(" Task start :"+ System.currentTimeMillis());
new Thread(futureTask,"t1").start();
System.out.println("main Thread end :"+ System.currentTimeMillis());
System.out.println(futureTask.get());
}
}
Task start :1657859359366
main Thread end :1657859359366
callable2
2048
- The task is performed only once
Next, two threads are started t1、t2 Perform tasks , It can be seen from the print results that the task was executed only once
public class CallableDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(()->{
System.out.println("callable");
return 2048;
});
new Thread(futureTask,"t1").start();
new Thread(futureTask,"t2").start();
System.out.println(futureTask.get());
}
}
callable
2048
边栏推荐
- Sword finger offer16- integer power bit operation of numeric value
- 牛客2021暑期训练1-H-Hash Function
- Top level makefile analysis of u-boot (3)
- 电商平台后台管理系统--->系统详细设计(订单管理模块)
- 三、索引优化
- H5 cloud image background reading and writing CAD files - Online CAD, web CAD, web browsing and editing CAD
- EN 1317-5道路约束系统产品—CE认证
- 3、 Index optimization
- ASTM e595-15 (2021) outgassing latest standard for degassing test
- “高内聚低耦合”的软件设计建议收藏
猜你喜欢

718. Longest repeating subarray

Docker---Docker安装,Docker上MySQl安装,并将项目部署在Docker上

What are the hardware of the cashier system?

抢先体验! 在浏览器里写 Flutter 是一种什么体验?

树和二叉树

ASTM E595-15(2021) Outgassing除气测试最新标准

Redis集群长时间连接不上问题Sending CLUSTER MEET messages to join the cluster Waiting for the cluster to join

动态规划 | 0-1背包问题
![[flutter -- actual combat] Introduction to flutter](/img/01/c588f75313580063cf32cc01677600.jpg)
[flutter -- actual combat] Introduction to flutter

电商平台后台管理系统--->系统详细设计(订单管理模块)
随机推荐
电商平台后台管理系统--->系统详细设计(用户登录、商品管理模块)
工程仪器振弦无线采集仪的采集数据发送方式及在线监测系统
LeetCode_ Sliding window_ Simple_ 643. Maximum average number of subarrays I
牛客2021暑期训练4-E-Tree Xor
LeetCode_ Sliding window_ Binary search_ Medium_ 713. Subarray with product less than k
A solution to the failure of NVIDIA SMI command
Puge - basic configuration usage of winscp and xshell of Honghu team on the code
聊一聊Spark实现TopN的几种方式
栈的应用—
Trees and binary trees
log4j.properties 日志详解
Niuke 2021 summer training 5-b-boxes
元宇宙带火的VR市场,字节也才摸到一点边
下采样 - 信号相位和混叠
Niuke 2021 summer training 1-a-alice and Bob
Implementing DDD based on ABP -- aggregation and aggregation root practice
Clear understanding of big end and small end
How to disable SSLv3 in Apache
牛客2021暑期训练3-J-Counting Triangles
收银系统的硬件有哪些?