gpt4 book ai didi

java - 什么时候使用线程,什么时候使用线程池?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:35 24 4
gpt4 key购买 nike

任何人都可以在这个示例中指导我 Thread 和 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));
}
}

最佳答案

请参阅 ThreadPoolExecutor 的文档:

Thread pools address two different problems:

they usually provideimproved performance when executing large numbers of asynchronoustasks, due to reduced per-task invocation overhead,

and they provide ameans of bounding and managing the resources, including threads,consumed when executing a collection of tasks.

Each ThreadPoolExecutoralso maintains some basic statistics, such as the number of completedtasks.

关于java - 什么时候使用线程,什么时候使用线程池?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49967592/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com