在这个例子中,有人能指导我吗?线程和ThreadPool之间有什么区别?哪个更好用.?缺点是什么?
我使用了线程池,为什么在这种情况下使用它是true还是false?
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));
}
}发布于 2018-04-22 15:41:54
线程池解决了两个不同的问题: 它们通常在执行大量异步任务时提供更好的性能,这是由于每个任务调用开销减少, 它们提供了一种在执行任务集合时使用的包围和管理资源(包括线程)的方法。 每个ThreadPoolExecutor还维护一些基本统计数据,例如已完成任务的数量。
发布于 2018-04-28 13:41:57
嗯,我认为ThreadPoolExecutor提供了更好的性能,因为它管理一个线程池,将实例化一个新线程、分配内存的开销降到最低.
如果你要启动成千上万的线程,它给你一些排队的功能,你必须自己编程.
线程和执行器是不同的工具,在不同的场景中使用.在我看来,就像问我为什么要使用ArrayList,而我可以使用HashMap?他们不一样..。
发布于 2018-04-28 17:42:58
何时使用:线程:我想管理线程创建,决定创建时间,并监视,同步,线程清理,自己。
执行者:我要专家/经理执行这些活动。
https://stackoverflow.com/questions/49967592
复制相似问题