Reputation: 641
Can anyone guide me in this Example Thread and ThreadPool What is the difference between them? Which is better to use ...? What is the drawback on ?
I used a threadpool and why use it in this case true or 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));
}
}
Upvotes: 3
Views: 3823
Reputation: 61
when to use: Threads: I want to manage thread creation, decide time of creation, and monitor, synchronization, thread cleanup, myself.
Executor: I want specialist/manager to perform these activities.
Upvotes: -1
Reputation: 1
Well, I thought that a ThreadPoolExecutor provided better performance for it manages a pool of threads, minimizing the overhead of instantiating a new thread, allocating memory...
And if you are going to launch thousands of threads, it gives you some queuing functionality you would have to program by yourself...
Threads & Executors are different tools, used on different scenarios... As I see it, is like asking why should I use ArrayList when I can use HashMap? They are different...
Upvotes: -1
Reputation: 28269
See the doc of ThreadPoolExecutor
:
Thread pools address two different problems:
they usually provide improved performance when executing large numbers of asynchronous tasks, due to reduced per-task invocation overhead,
and they provide a means of bounding and managing the resources, including threads, consumed when executing a collection of tasks.
Each ThreadPoolExecutor also maintains some basic statistics, such as the number of completed tasks.
Upvotes: 5