Use the thread pool (with lambda use)

Use the thread pool (with lambda use)

since jdk1.5 provided Executors factory class provides the thread pool at the java.util.concurrent package for the production of the thread pool, providing four Executors thread pool

-newFixedThreadPool: create a thread pool, the thread pool thread to reuse a fixed number of runs from a shared unbounded queue.
-newCachedThreadPool: create a thread pool that creates new threads as needed, but when available will reuse previously constructed threads.
-newSingleThreadExecutor: Create a program to perform a single work queue threads never run community use. Support for regular and periodic task execution.
-newWorkStealingPool: created using all available processors as its target level of work-stealing parallel thread pool. It will only be performed with the sole task of worker threads to ensure that all tasks are performed in a specified order (FIFO, LIFO, priorities).

The procedures (for example in newSingleThreadExecutor):

  1. Create a thread pool, thread pool to create a fixed number using the static method newFixedThreadPool Executors of ().
  2. Using lambda implement runnable interfaces, override the run method, set the thread task
  3. The call ExecutorService submit transfer threaded tasks, open thread, run method
  4. Destruction of ExecutorService thread calls shutdown (not recommended)
        //创建使用单个线程的线程池
        ExecutorService es = Executors.newFixedThreadPool(2);
        //使用lambda实现runnable接口
        Runnable task = ()->{
            System.out.println(Thread.currentThread().getName()+"创建了一个新的线程执行");
        };
        //调用submit传递线程任务,开启线程
        es.submit(task);
        es.submit(task);
        es.submit(task);
        
        //调用ExecutorService的shutdown销毁线程(不建议执行)
        //es.shutdown();
        //es.submit(task);//关闭线程池后再次使用会抛异常

At this time, submitted a three-threaded task, print the results:

pool-1-thread-1创建了一个新的线程执行
pool-1-thread-1创建了一个新的线程执行
pool-1-thread-2创建了一个新的线程执行

Only two threads in the thread pool, thread pool will remain open, find the task finished using 1 thread return the pool-1-thread-1, Task 2 can continue to use.
At this point if you call es.shutdown (); will destroy the thread pool, open thread will throw an exception again.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@ea30797 
发布了2 篇原创文章 · 获赞 1 · 访问量 133

Guess you like

Origin blog.csdn.net/weixin_43881455/article/details/104003361