有人能帮我解释一下线程和线程池的区别吗?哪一个更好用?它们各自的缺点是什么?
我在这个例子中使用了线程池,而在这种情况下使用它是正确的还是错误的?
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));
}
}
try
块。 - Turing85