Java线程和多线程——线程池基础

Posted EthanPark

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java线程和多线程——线程池基础相关的知识,希望对你有一定的参考价值。

Java 线程池管理多个工作线程,其中包含了一个队列,包含着所有等待被执行的任务。开发者可以通过使用ThreadPoolExecutor来在Java中创建线程池。

线程池是Java中多线程的一个重要概念,因为通过Thread模型来控制多线程是非常麻烦以及易错的一个过程。过多的释放线程会造成线程调度的变慢以及过度的消耗内存。而频繁的创建线程,也没有很好的复用线程,所以有了线程池的概念。Java中的线程池就是ExecutorService
其中包含了一些基本的关闭,执行等功能

ExecutorService举例

java.util.concurrent.Executors提供了java.util.concurrent.Executor接口的实现,并且用来提供线程池服务。参考如下代码:

package com.sapphire.threadpool;

public class WorkerThread implements Runnable 

    private String command;

    public WorkerThread(String s)
        this.command=s;
    

    @Override
    public void run() 
        System.out.println(Thread.currentThread().getName()+" Start. Command = "+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+" End.");
    

    private void processCommand() 
        try 
            Thread.sleep(5000);
         catch (InterruptedException e) 
            e.printStackTrace();
        
    

    @Override
    public String toString()
        return this.command;
    

上面的代码是一个简单的实现了RunnableWorkThread。下面展示的是线程池代码,通过Executors框架创建的固定线程数的线程池。

package com.journaldev.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleThreadPool 

    public static void main(String[] args) 
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) 
            Runnable worker = new WorkerThread("" + i);
            executor.execute(worker);
          
        executor.shutdown();
        while (!executor.isTerminated()) 
        
        System.out.println("Finished all threads");
    

上面个程序中的ExecutorService executor就是一个线程池,其调用的函数Executors.newFixedThreadPool(int size)函数来生成固定的线程数的一个线程池。在程序中,我们通过一个for循环提交了10个任务,因为我们配置了线程池的大小,所以其中的线程数最大始终是5不会出现无限创建线程的那种情况,当同时有其他的任务提交到线程池的时候,线程池会持续的等待,直到有一个任务完成,那么另一个任务就会从等待队列里面出来,进入执行队列来执行。

下面是上面程序的输出内容:

pool-1-thread-2 Start. Command = 1
pool-1-thread-4 Start. Command = 3
pool-1-thread-1 Start. Command = 0
pool-1-thread-3 Start. Command = 2
pool-1-thread-5 Start. Command = 4
pool-1-thread-4 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
pool-1-thread-3 End.
pool-1-thread-3 Start. Command = 8
pool-1-thread-2 End.
pool-1-thread-2 Start. Command = 9
pool-1-thread-1 Start. Command = 7
pool-1-thread-5 Start. Command = 6
pool-1-thread-4 Start. Command = 5
pool-1-thread-2 End.
pool-1-thread-4 End.
pool-1-thread-3 End.
pool-1-thread-5 End.
pool-1-thread-1 End.
Finished all threads

其中输出的内容也说明了在线程池中有5个线程,名字从pool-1-thread-1pool-1-thread-5,由叫这5个名字的线程负责执行提交到线程池的任务。

ThreadPoolExecutor举例

Executors类通过ThreadPoolExecutor提供了ExecutorService的简单实现,但是,ThreadPoolExecutor提供的特性更多。我们可以在创建ThreadPoolExecutor
时指定线程池的大小,也可以定制RejectedExecutionHandler的实现来处理无法加入工作队列的任务。

下面是我们的自定义的RejectedExecutionHandler:

package com.sapphire.threadpool;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;

public class RejectedExecutionHandlerImpl implements RejectedExecutionHandler 

    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) 
        System.out.println(r.toString() + " is rejected");
    

ThreadPoolExecutor会提供一些方法,令开发者可以知道目前线程池的状态,比如,线程池大小,活跃的线程数,任务队列长度等信息。所以,下面我写了一个监控线程来定期展示线程池的状态信息。

package com.sapphire.threadpool;

import java.util.concurrent.ThreadPoolExecutor;

public class MyMonitorThread implements Runnable

    private ThreadPoolExecutor executor;
    private int seconds;
    private boolean run=true;

    public MyMonitorThread(ThreadPoolExecutor executor, int delay)
    
        this.executor = executor;
        this.seconds=delay;
    
    public void shutdown()
        this.run=false;
    
    @Override
    public void run()
    
        while(run)
                System.out.println(
                    String.format("[monitor] [%d/%d] Active: %d, Completed: %d, Task: %d, isShutdown: %s, isTerminated: %s",
                        this.executor.getPoolSize(),
                        this.executor.getCorePoolSize(),
                        this.executor.getActiveCount(),
                        this.executor.getCompletedTaskCount(),
                        this.executor.getTaskCount(),
                        this.executor.isShutdown(),
                        this.executor.isTerminated()));
                try 
                    Thread.sleep(seconds*1000);
                 catch (InterruptedException e) 
                    e.printStackTrace();
                
        

    

下面是使用ThreadPoolExecutor的实现方案。

package com.sapphire.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class WorkerPool 

    public static void main(String args[]) throws InterruptedException
        //RejectedExecutionHandler implementation
        RejectedExecutionHandlerImpl rejectionHandler = new RejectedExecutionHandlerImpl();
        //Get the ThreadFactory implementation to use
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        //creating the ThreadPoolExecutor
        ThreadPoolExecutor executorPool = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), threadFactory, rejectionHandler);
        //start the monitoring thread
        MyMonitorThread monitor = new MyMonitorThread(executorPool, 3);
        Thread monitorThread = new Thread(monitor);
        monitorThread.start();
        //submit work to the thread pool
        for(int i=0; i<10; i++)
            executorPool.execute(new WorkerThread("cmd"+i));
        

        Thread.sleep(30000);
        //shut down the pool
        executorPool.shutdown();
        //shut down the monitor thread
        Thread.sleep(5000);
        monitor.shutdown();

    

需要注意的是,当我们在创建ThreadPoolExecutor的时候,我们限制了线程池的大小最小为2,最大大小为4,而工作队列长度为2。所以如果线程池中4个运行的任务的时候,再提交更多任务的时候,则至多只能提交两个处于等待状态的任务。如果再提交更多的话,则会由RejectedExecutionHandlerImpl来处理。

cmd8 is rejected
cmd9 is rejected
[monitor] [0/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 4, Completed: 0, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-4 End.
pool-1-thread-1 End.
pool-1-thread-2 End.
pool-1-thread-3 End.
pool-1-thread-1 Start. Command = cmd3
pool-1-thread-4 Start. Command = cmd2
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
[monitor] [4/2] Active: 2, Completed: 4, Task: 6, isShutdown: false, isTerminated: false
pool-1-thread-1 End.
pool-1-thread-4 End.
[monitor] [4/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [2/2] Active: 0, Completed: 6, Task: 6, isShutdown: false, isTerminated: false
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true
[monitor] [0/2] Active: 0, Completed: 6, Task: 6, isShutdown: true, isTerminated: true

可以观察线程池在各个状态,如:活跃状态数,任务的完成数等等信息的变化。我们通过调用shutdown()方法来结束提交任务的执行,并结束了线程池。

如果开发者希望来延迟执行一个任务,或者定期执行一个任务的话,开发者可以使用ScheduledThreadPoolExecutor类来完成这个功能。

以上是关于Java线程和多线程——线程池基础的主要内容,如果未能解决你的问题,请参考以下文章

26Java并发性和多线程-线程池

Java使用线程池和多线程实现并行计算(案例一)

Java线程和多线程(十三)——Callable,Future,FutureTask

Spring Batch 连接池和多线程

SpringBoot几种定时任务的实现方式 和多线程执行任务

多线程——java线程池简介