Use of SingleThreadExecutor

Source: Internet
Author: User

Use of SingleThreadExecutor

1. SingleThreadExecutor is like a FixedThreadPool with a thread number of 1.

2. If multiple tasks are submitted to SingleThreadExecutor, these tasks are queued. The output result shows that the task is executed in the submission order.

3. SingleThreadExecutor serializes all submitted tasks and maintains its own (hidden) hanging task queue .??? (Do not understand)

4. SingleThreadExecutor ensures that only a unique task is running in any thread. (When multiple threads use the same file system, SingleThreadExecutor can be used for synchronization)

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class SingleThreadExecutor {public static void main(String[] args) {ExecutorService executorService=Executors.newSingleThreadExecutor();for(int i=0;i<5;i++){executorService.execute(new LiftOff());}executorService.shutdown();}static public class LiftOff implements Runnable{protected int countDown=10;private static int taskCount=0;private final int id=taskCount++;public LiftOff(){}public LiftOff(int countDown){this.countDown=countDown;}public String status(){return "#"+id+"("+(countDown>0?countDown:"Liftoff!")+"),";}public void run(){while(countDown-->0){System.out.print(status());Thread.yield();}}}}//output//#0(9),#0(8),#0(7),#0(6),#0(5),#0(4),#0(3),#0(2),#0(1),#0(Liftoff!),//#1(9),#1(8),#1(7),#1(6),#1(5),#1(4),#1(3),#1(2),#1(1),#1(Liftoff!),//#2(9),#2(8),#2(7),#2(6),#2(5),#2(4),#2(3),#2(2),#2(1),#2(Liftoff!),//#3(9),#3(8),#3(7),#3(6),#3(5),#3(4),#3(3),#3(2),#3(1),#3(Liftoff!),//#4(9),#4(8),#4(7),#4(6),#4(5),#4(4),#4(3),#4(2),#4(1),#4(Liftoff!),


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.