当前位置:网站首页>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();
}
}边栏推荐
- Elk - x-pack set user password
- P2580 "so he started the wrong roll call"
- Add auto thumbnail function for WordPress related log plug-ins
- 2020-07 study notes sorting
- Publish WordPress database cache plug-in: DB cache reloaded 3.1
- C# 将OFD转为PDF
- 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
- Is the SSL certificate reliable in ensuring the information security of the website?
- Software project management 7.1 Basic concept of project schedule
- Streaking? Baa!
猜你喜欢
随机推荐
Take you to know about direct insertion sorting (C language)
[JUC supplementary] atomic class, unsafe
arguments.callee 实现函数递归调用
Guice integrated properties configuration
The tutor transferred me 800 yuan and asked me to simulate a circuit (power supply design)
Memory mapping image of the grayloc module in the surfacefinder process
解决swagger文档接口404的问题
程序员常用的命令符
C # apply many different fonts in PDF documents
.net core 抛异常对性能影响的求证之路
Uncaught TypeError: Cannot set property ‘next‘ of undefined 报错解决
ObjectInputStream读取文件对象ObjectOutputStream写入文件对象
Use cache to reduce network requests
CVPR 2022 𞓜 text guided entity level image manipulation manitrans
[C language] anonymous/unnamed struct & Union
JS to realize the rotation chart (riding light). Pictures can be switched left and right. Moving the mouse will stop the rotation
[Chapter II Relationship between genes and chromosomes] summary of biological knowledge - Biology in grade one of senior high school
安全工程师发现PS主机重大漏洞 用光盘能在系统中执行任意代码
Queuing theory model
Is the SSL certificate reliable in ensuring the information security of the website?









