Java固定大小线程池执行程序示例

在上一教程中,我们了解了基本线程池执行程序,该线程 Actuator 具有无限数量的线程进入该池,并且是示例用法。现在来看固定大小的线程池执行程序的示例,示例通过限制线程池中的最大线程数来帮助提高性能和更好地利用系统资源。

1)创建要执行的任务

显然,第一步是要执行一个要使用执行程序执行的任务。

class Task implements Runnable
{
    private String name;
    public Task(String name)
    {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    @Override
    public void run()
    {
        try
        {
            Long duration = (long) (Math.random() * 10);
            System.out.println("Doing a task during : " + name);
            TimeUnit.SECONDS.sleep(duration);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}

2)使用 Actuator 执行任务

现在,您要做的就是创建一个ThreadPoolExecutor具有固定大小的实例,并将要执行的任务传递到其execute()方法中。

package com.how2codex.demo.multithreading;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class FixedThreadPoolExecutorExample
{
    public static void main(String[] args)
    {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(4);
        for (int i = 0; i < 10; i++)
        {
            Task task = new Task("Task " + i);
            System.out.println("A new task has been added : " + task.getName());
            executor.execute(task);
        }
        System.out.println("Maximum threads inside pool " + executor.getMaximumPoolSize());
        executor.shutdown();
    }
}
Output:
A new task has been added : Task 0
A new task has been added : Task 1
A new task has been added : Task 2
A new task has been added : Task 3
A new task has been added : Task 4
A new task has been added : Task 5
A new task has been added : Task 6
A new task has been added : Task 7
Doing a task during : Task 0
Doing a task during : Task 2
Doing a task during : Task 1
A new task has been added : Task 8
Doing a task during : Task 3
A new task has been added : Task 9
Maximum threads inside pool 4
Doing a task during : Task 4
Doing a task during : Task 5
Doing a task during : Task 6
Doing a task during : Task 7
Doing a task during : Task 8
Doing a task during : Task 9

重要事项:

1)newFixedThreadPool()方法可随时创建具有最大线程数的执行程序。如果您发送的任务多于线程数,则其余任务将被阻塞,直到有空闲线程来处理它们为止。此方法将最大线程数作为您希望在执行程序中拥有的参数。在您的情况下,您创建了一个具有四个线程的执行程序。

2)Executors该类还提供了newSingleThreadExecutor()方法。这是固定大小的线程 Actuator 的极端情况。它创建的执行程序只有一个线程,因此一次只能执行一个任务。

saigon has written 1445 articles

Leave a Reply