使用线程池

本文探讨了Java中线程池的使用,通过创建固定大小的线程池来提高并发性能,减少线程创建销毁的开销。ExecutorService和Executors工具类被用来创建线程池,execute和submit方法执行任务。通过调用shutdown方法关闭线程池,确保资源的有序释放。线程池的配置参数如核心池大小、最大线程数和空闲线程存活时间等,对于系统性能有着重要影响。
摘要由CSDN通过智能技术生成

背景:经常创建或销毁,使用量大,并发情况,性能影响大

思路:提前创多个线程,放线程池中,使用直接拿,用完放回池,可避免频繁创建销毁,重复利用,类似交通工具

好处:

减少创建新线程时间

重复利用线程池中线程,不需每次创建

便于线程管理:

核心池大小

最大线程数

线程没有任务时最多保持多长时间后会终止

使用线程池:

jdk5:ExecutorService和Executors

ExecutorService:线程池接口,子类ThreadPoolExecutor

void execute(Runnable command):执行任务,无返回值,一般执行Runnable

<T>Future<T>submit(Callable)task:执行任务,有返回值,一般来执行Callable

void shutDown():关闭线程池

Executors:工具类,线程池工厂类,用于创建并返回不同类型的线程池

package com.wuming.thread;

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

//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //1.创建服务,创建线程池
        //newFixedThreadPool 参数为:线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);
        //执行
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        //2.关闭链接
        service.shutdown();
    }
}
class MyThread implements Runnable{

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值