例如: 我设计了一个最多有5个线程的线程池来完成工作。
public class ThreadPool{
// Ignore the Task class
private LinkedList<Task> tasks;
Executor[] executors = new Executor[5];
private static ThreadPool pool = null;
private ThreadPool() {
tasks = new LinkedList<Task>();
for (int i = 0; i < 5; i++) {
executors[i] = new Executor(i);
}
}
public static ThreadPool getInstance() {
if (pool == null) {
pool = new ThreadPool();
}
return pool;
}
public void addTask(Task task) {
/** igore code here*/
}
private class Executor extends Thread {
private int i;
public Executor(int i) {
this.i = i;
start();
}
public void run() {
Task task = null;
synchronized (tasks) {
if (tasks.size() == 0) {
System.out.println("tasks's size is : " + tasks.size());
try {
while (tasks.size() == 0) {
tasks.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (tasks.size() > 0)
task = tasks.removeFirst();
}
if (task != null) {
/** ignore code here */
}
}
}
}
不幸的是,同步不起作用。但是当我将同步块放入
时synchronized (ThreadPool.this) {
...
}
它有效。
所以,我想知道为什么内部类方法不能同步外部类中的对象。
希望得到详细解答。