Controlling Task execution order with ExecutorService

前端 未结 8 1962
一生所求
一生所求 2020-12-02 14:30

I have a process which delegates asynch tasks to a pool of threads. I need to ensure that certain tasks are executed in order. So for example

Tasks arrive in order<

8条回答
  •  爱一瞬间的悲伤
    2020-12-02 15:00

    You can use Executors.newSingleThreadExecutor(), but it will use only one thread to execute your tasks. Another option is to use CountDownLatch. Here is a simple example:

    public class Main2 {
    
    public static void main(String[] args) throws InterruptedException {
    
        final CountDownLatch cdl1 = new CountDownLatch(1);
        final CountDownLatch cdl2 = new CountDownLatch(1);
        final CountDownLatch cdl3 = new CountDownLatch(1);
    
        List list = new ArrayList();
        list.add(new Runnable() {
            public void run() {
                System.out.println("Task 1");
    
                // inform that task 1 is finished
                cdl1.countDown();
            }
        });
    
        list.add(new Runnable() {
            public void run() {
                // wait until task 1 is finished
                try {
                    cdl1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                System.out.println("Task 2");
    
                // inform that task 2 is finished
                cdl2.countDown();
            }
        });
    
        list.add(new Runnable() {
            public void run() {
                // wait until task 2 is finished
                try {
                    cdl2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
                System.out.println("Task 3");
    
                // inform that task 3 is finished
                cdl3.countDown();
            }
        });
    
        ExecutorService es = Executors.newFixedThreadPool(200);
        for (int i = 0; i < 3; i++) {
            es.submit(list.get(i));
        }
    
        es.shutdown();
        es.awaitTermination(1, TimeUnit.MINUTES);
    }
    }
    

提交回复
热议问题