Java 线程池

启动一个新线程,成本是比较高的,因为需要与操作系统进行交互。
而使用线程池可以很好地提高性能,尤其当需要创建大量生存期很短的线程时,更应该考虑使用线程池。
线程池里的每一条线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下次被调用。

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

/**
 * Created by Administrator on 2018/10/21 16:26 in Beijing.
 */

public class ThreadPoolTest {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        pool.submit(new ThreadPoolRunnable());
        pool.submit(new ThreadPoolRunnable());
        pool.submit(new ThreadPoolRunnable());

        pool.shutdown();  // 此时线程池才会关闭
    }
}

class ThreadPoolRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" + i);
        }
    }
}

输出如下

pool-1-thread-2	0
pool-1-thread-3	0
pool-1-thread-1	0
pool-1-thread-3	1
pool-1-thread-2	1
pool-1-thread-3	2
pool-1-thread-1	1
pool-1-thread-1	2
pool-1-thread-3	3
pool-1-thread-2	2
pool-1-thread-3	4
pool-1-thread-3	5
pool-1-thread-3	6
pool-1-thread-3	7
pool-1-thread-3	8
pool-1-thread-1	3
pool-1-thread-1	4
pool-1-thread-1	5
pool-1-thread-1	6
pool-1-thread-3	9
pool-1-thread-2	3
pool-1-thread-2	4
pool-1-thread-2	5
pool-1-thread-2	6
pool-1-thread-2	7
pool-1-thread-2	8
pool-1-thread-1	7
pool-1-thread-2	9
pool-1-thread-1	8
pool-1-thread-1	9

Process finished with exit code 0

注意: 如果 没有最后一行,那么程序并不会退出。

pool.shutdown();  // 此时线程池才会关闭
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值