[問題] 關於Executor運作原理
自從Java SE5後,提供了Executors管理Thread,
但是對於一些執行上的問題,我還是有一些疑惑,以下是測試程式碼:
public class ThreadTest {
public static void main(String[] args) {
ThreadTest t = new ThreadTest();
ExecutorService exec = Executors.newFixedThreadPool(
1, t.new MyThreadFactory());
for (int i=0;i<5;i++) {
exec.execute(t.new MyRunnable(i));
}
exec.shutdown();
}
public class MyThread extends Thread {
private int id;
public MyThread(Runnable r, int id) {
super(r);
this.id = id;
}
public void run() {
super.run();
System.out.println("Thread ID: " + this.id);
}
}
public class MyRunnable implements Runnable {
private int id;
public MyRunnable(int id) {
this.id = id;
}
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("Runnable ID: " + this.id);
}
}
public class MyThreadFactory implements ThreadFactory {
private int id;
public MyThreadFactory() {
this.id = 0;
}
@Override
public Thread newThread(Runnable r) {
MyThread t = new MyThread(r, id++);
return t;
}
}
}
例子中,我丟了五個Runnable進ExecutorService執行,對於ThreadPool我不是很了解。
ThreadFactory產生了一個Thread,他會把五個Runnable都印完之後,
才會印他自己的ID。可是感覺上應該是一個Thread對到一個Runnable,
怎麼會五個Runnable都丟給了同一個Thread去執行呢?
它是怎麼做到讓五個Runnable的run()疊在一起變成super.run()?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 61.222.86.99
推
11/21 14:27, , 1F
11/21 14:27, 1F
推
11/21 20:50, , 2F
11/21 20:50, 2F
→
11/21 21:22, , 3F
11/21 21:22, 3F
→
11/21 21:24, , 4F
11/21 21:24, 4F
→
11/22 09:59, , 5F
11/22 09:59, 5F
→
11/22 10:01, , 6F
11/22 10:01, 6F
→
11/22 10:06, , 7F
11/22 10:06, 7F
討論串 (同標題文章)
以下文章回應了本文 (最舊先):
完整討論串 (本文為第 1 之 3 篇):