何时使用Thread以及何时使用Threadpool?

时间:2018-04-22 15:25:35

标签: java multithreading threadpool

任何人都可以在这个示例中指导我Thread和ThreadPool它们之间有什么区别?哪个更好用......?有什么缺点?

我使用了线程池,为什么在这种情况下使用它是真还是假?

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

class ThreeThread implements Runnable {

    String c;
    Semaphore s1;
    Semaphore s2;

    public ThreeThread(String s, Semaphore s1, Semaphore s2) {
        this.c = s;
        this.s1 = s1;
        this.s2 = s2;
    }

    @Override
    public void run() {
        while (true) {
            try {
                s1.acquire();
                Thread.sleep(400);
                System.out.println(c);
                s2.release();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                System.out.println(e);
            }
        }
    }

    public static void main(String[] args) {
        Semaphore sm1 = new Semaphore(1);
        Semaphore sm2 = new Semaphore(0);
        Semaphore sm3 = new Semaphore(0);

        ExecutorService es = Executors.newFixedThreadPool(3);

        es.execute(new ThreeThread("1", sm1, sm2));
        es.execute(new ThreeThread("2", sm2, sm3));
        es.execute(new ThreeThread("3", sm3, sm1));
    }
}

3 个答案:

答案 0 :(得分:3)

请参阅ThreadPoolExecutor的文档:

  

线程池解决了两个不同的问题:

     他们通常提供   在执行大量异步时提高了性能   任务,由于减少了每个任务的调用开销,

     

他们提供了一个   绑定和管理资源的方法,包括线程,   在执行任务集合时消耗。

     

每个ThreadPoolExecutor   还保留了一些基本的统计数据,比如已完成的数量   任务。

答案 1 :(得分:-1)

好吧,我认为ThreadPoolExecutor为管理线程池提供了更好的性能,最大限度地减少了实例化新线程,分配内存的开销......

如果您要发布数千个线程,它会为您提供一些排队功能,您必须自己编程...

线程&执行器是不同的工具,在不同的场景中使用......正如我所看到的,就像问我为什么要在使用HashMap时使用ArrayList?他们是不同的......

答案 2 :(得分:-1)

何时使用: 线程:我想管理线程创建,决定创建时间,监视,同步,线程清理,我自己。

执行人:我希望专家/经理来完成这些活动。