What are the advantages of using an ExecutorService?

前端 未结 8 1049
孤城傲影
孤城傲影 2020-11-27 12:45

What is the advantage of using ExecutorService over running threads passing a Runnable into the Thread constructor?

8条回答
  •  -上瘾入骨i
    2020-11-27 13:24

    An advantage I see is in managing/scheduling several threads. With ExecutorService, you don't have to write your own thread manager which can be plagued with bugs. This is especially useful if your program needs to run several threads at once. For example you want to execute two threads at a time, you can easily do it like this:

    ExecutorService exec = Executors.newFixedThreadPool(2);
    
    exec.execute(new Runnable() {
      public void run() {
        System.out.println("Hello world");
      }
    });
    
    exec.shutdown();
    

    The example may be trivial, but try to think that the "hello world" line consists of a heavy operation and you want that operation to run in several threads at a time in order to improve your program's performance. This is just one example, there are still many cases that you want to schedule or run several threads and use ExecutorService as your thread manager.

    For running a single thread, I don't see any clear advantage of using ExecutorService.

提交回复
热议问题