当前位置:网站首页>Four ways to create threads
Four ways to create threads
2022-06-11 12:03:00 【java-zh】
1、 Inherit Thread class
public class ThreadTest extends Thread {
public void run(){
System.out.println(Thread.currentThread().getName()+"----thread Of run Method is executing ....");
}
}
2、 Realization Runnable Interface
public class RunnableTest implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"----runnable Of run Method is executing ....");
}
}3、 Realization Callable Interface
public class CallableTest implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName()+"----callable Of run Method is executing ....");
return 1;
}
}4、 Use Executors Tool class creates thread pool ( There are four thread pools )
public class PoolThreadTest implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"----pool Of run Method is executing ....");
}
public static void main(String[] args) {
ExecutorService executorService1 = Executors.newSingleThreadExecutor();
PoolThreadTest poolThreadTest = new PoolThreadTest();
for (int i = 0; i < 2; i++) {
executorService1.execute(poolThreadTest);
}
System.out.println(" The thread task begins to execute ");
executorService1.shutdown();
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
scheduledThreadPool.schedule(new Runnable() {
@Override
public void run() {
System.out.println(" Execute in three seconds ......");
}
},3, TimeUnit.SECONDS);
scheduledThreadPool.shutdown();
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
for (int i = 0; i < 2; i++) {
fixedThreadPool.execute(new PoolThreadTest());
}
fixedThreadPool.shutdown();
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
for (int i = 0; i <2; i++) {
cachedThreadPool.execute(new PoolThreadTest());
}
cachedThreadPool.shutdown();
}
}Be careful
Explanation of four thread pools
newSingleThreadExecutor: Returns a thread pool ( This thread pool has only one thread ), This thread pool can be used after a thread dies ( Or when something goes wrong ) Restart a thread to replace the original thread to continue execution , The biggest feature of this thread is that it can ensure the sequential execution of various tasks , And no more than one thread will be active at any given time .
newScheduledThreadPool: Create a thread pool , It can be scheduled to run commands after a given delay or to execute on a regular basis .
newCachedThreadPool: Create a cacheable thread pool , If the thread pool length exceeds processing requirements , Free threads can be recycled flexibly , If there is no recovery , New thread . In the use of CachedThreadPool when , Be sure to control the number of tasks , otherwise , Because a lot of threads are running at the same time , It will cause system paralysis .
newFixedThreadPool: Create a thread pool that specifies the number of worker threads . Create a worker thread every time a task is submitted , If the number of worker threads reaches the initial maximum number of thread pools , Then put the submitted tasks into the pool queue .
test
public class Test {
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
threadTest.start();
RunnableTest test = new RunnableTest();
Thread thread1 = new Thread(test);
thread1.start();
FutureTask<Integer> futureTask = new FutureTask<Integer>(new CallableTest());
Thread thread2 = new Thread(futureTask);
thread2.start();
}
}边栏推荐
- 17.5 concept, usage, deadlock demonstration and solution of mutex
- Where is it safer to open an account for soda ash futures? How much does it cost to buy soda ash futures?
- How should ordinary people choose annuity insurance products?
- JS merge two objects (interview questions)
- Zhejiang University and Microsoft Asia Research Institute released a new method of video recognition, which can recognize video frame by frame without data marking, or can be used for sign language tr
- Etcd introduction
- Smart sidebar plug-in: Mo widgets
- JS 加法乘法错误解决 number-precision
- JS addition and multiplication error resolution number precision
- Jest unit test description config json
猜你喜欢
![[file upload vulnerability 06] server file content detection and bypass experiment + image horse production method (based on upload-labs-14 shooting range)](/img/30/79516390c2b2b50a224eaa84a0c1c9.jpg)
[file upload vulnerability 06] server file content detection and bypass experiment + image horse production method (based on upload-labs-14 shooting range)

yapi安装

web开发选型,web开发毕业谁

C# 设置或验证 PDF中的文本域格式

MSF CS OpenSSL traffic encryption

浙大联合微软亚研院发布视频识别新方法,可对视频逐帧识别且无需,数据标记,或可用于手语翻译等

导师转我800块,让我仿真一个电路(电源设计)

Use compiler option ‘--downlevelIteration‘ to allow iterating of iterators 报错解决

Hang up the interviewer

JS to realize the rotation chart (riding light). Pictures can be switched left and right. Moving the mouse will stop the rotation
随机推荐
Fast build elk7.3
《公司理财师专业能力》笔记
2022 | framework for Android interview -- Analysis of the core principles of binder, handler, WMS and AMS!
Intermediate web development engineer, interview questions + Notes + project practice
导师转我800块,让我仿真一个电路(电源设计)
.net core 抛异常对性能影响的求证之路
17.5 concept, usage, deadlock demonstration and solution of mutex
C# 将OFD转为PDF
Add auto thumbnail function for WordPress related log plug-ins
微信web开发者,如何学习web开发
Use cache to reduce network requests
Linux忘记MySQL密码后修改密码
微信授权获取手机号码
带你了解直接插入排序(C语言)
2019年书单
[fragmentary thoughts] thoughts on wavelength, wave velocity and period
How should ordinary people choose annuity insurance products?
Hamiltonian graph
[JUC supplementary] immutable object, shared meta mode, final principle
广东市政安全施工资料管理软件2022新表格来啦