关于线程有关问题,被彻底整晕了
关于线程问题,被彻底整晕了
直接上代码,网上看来的
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++)
{
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
while (getQueueSize(tpe.getQueue()) >= queueDeep)
{
System.out.println("队列已满,等3秒再添加任务");
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
TaskThreadPool ttp = new TaskThreadPool(i);
System.out.println("put i:" + i);
tpe.execute(ttp);
}
tpe.shutdown();
}
private synchronized int getQueueSize(Queue queue)
{
return queue.size();
}
public static void main(String[] args)
{
ThreadPoolExecutorTest test = new ThreadPoolExecutorTest();
test.createThreadPool();
}
我有一点不明白,方法getQueueSize为什么是synchronized ?这里只有主线程访问了createThreadPool()方法,不是多个线程在访问,何必要在一个方法上加synchronized 这个呢?
请大虾们赐教
------解决方案--------------------
是需要加的,你的这个queue其实是有其他的线程在操作的,就是线程池框架里面,执行一个任务,都会从queue中弹出一个任务。具体参看源码
直接上代码,网上看来的
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++)
{
try
{
Thread.sleep(1);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
while (getQueueSize(tpe.getQueue()) >= queueDeep)
{
System.out.println("队列已满,等3秒再添加任务");
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
TaskThreadPool ttp = new TaskThreadPool(i);
System.out.println("put i:" + i);
tpe.execute(ttp);
}
tpe.shutdown();
}
private synchronized int getQueueSize(Queue queue)
{
return queue.size();
}
public static void main(String[] args)
{
ThreadPoolExecutorTest test = new ThreadPoolExecutorTest();
test.createThreadPool();
}
我有一点不明白,方法getQueueSize为什么是synchronized ?这里只有主线程访问了createThreadPool()方法,不是多个线程在访问,何必要在一个方法上加synchronized 这个呢?
请大虾们赐教
------解决方案--------------------
是需要加的,你的这个queue其实是有其他的线程在操作的,就是线程池框架里面,执行一个任务,都会从queue中弹出一个任务。具体参看源码