1、Executors在于java.util.comcurrent.包下,Executors.newFixedThreadPool(n)创建容器大小为n的线程池,表示正在执行中的线程只有n个,

实践代码如下:

public class TestExecute {

    public static void main(String[] args) {
        Executor exe = Executors.newFixedThreadPool(2);

        for (int i = 0; i < 3; i++) {
            ExeThreads ex = new ExeThreads();
            exe.execute(ex);

        }

    }

}

class ExeThreads implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println("run start-----------------" + System.currentTimeMillis());
            Thread.sleep(15 * 1000);
            System.out.println("run end-----------------" + System.currentTimeMillis());

        }
        catch (InterruptedException e) {

            e.printStackTrace();
        }

    }

}

实验结果如下:

 

事例总结:线程池大小为2,但是要执行的线程是3个。所以正在执行的线程只有2个,正在执行的2个线程的开始时间为1536907573338,2个线程的结束时间为1536907588338,第3个线程的开始时间,刚刚好是前面2个线程执行结束时间。

GitHub 加速计划 / th / ThreadPool
8
0
下载
A simple C++11 Thread Pool implementation
最近提交(Master分支:4 个月前 )
9a42ec13 - 11 年前
fcc91415 - 11 年前
Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐