I encountered a problem:Will inner class method cannot synchronized the object in outer class? A answer from stackoverflow told me : No. But I really want to know the reason.
For example: I designed a thread pool with at most 5 threads to do work.
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 */
}
}
}
}
Unfortunately, the synchronized doesn't work. But when I put the synchronized block into
synchronized (ThreadPool.this) {
...
}
it works.
So, i want to know why inner class method cannot synchronized the object in outer class.
Hope for a detailed answer.