这段网上代码的synchronized加的莫名其妙,还是理解不了.....
public class ThreadPoolExecutorTest
{
private static int queueDeep = 4;
public void createThreadPool()
{
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 4, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(queueDeep), new ThreadPoolExecutor.DiscardOldestPolicy());
// 向线程池中添加 10 个任务
for (int i = 0; i < 10; i++)
{
//.....
while (getQueueSize(tpe.getQueue()) >= queueDeep)
{
System.out.println("队列已满,等3秒再添加任务");
}
}
}
private synchronized int getQueueSize(Queue queue)
{
return queue.size();
}
public static void main(String[] args)
{
ThreadPoolExecutorTest test = new ThreadPoolExecutorTest();
test.createThreadPool();
}
}
主体代码就是这些,这里有一个方法getQueueSize,被加了锁,这说明,如果有多个线程同时访问类ThreadPoolExecutorTest 的getQueueSize方法时,只有获得锁的线程,才能进行访问,
问题现在是,只有一个主线程在访问这个方法吧(通过createThreadPool方法),这里还加这个锁有什么意思啊!我自己做了测试不加也没啥啊,还是我理解错了.....
[解决办法]
本人认为没有必要加入
1 ArrayBlockingQueue是线程安全的
下面是size方法的源代码
public int size() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
可以看出对于成员count来说是线程安全的。也就是说在任何时间点任何线程访问该实例queue的size都是一致的
2 在看一下getQueueSize方法
private synchronized int getQueueSize(Queue queue) {
return queue.size();
}
改方法上面加入了同步关键字synchronized,改方法锁定的对象是this也就是自己本身的实例。但是这个方法的调用者只是main函数,并没有其他的线程调用,那么说synchronized
没有任何意义。再加上1上面的说的ArrayBlockingQueue本身是线程安全的,加锁的对象也是不一样的,根本就没有任何关系。
所以纵1,2点所说,这个synchronized没有任何作用。只是本人观点。不同观点请追加。