0 0

ThreadPoolExecutor 用法的疑问10

import java.io.Serializable;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TestThreadPool {

private static int produceTaskSleepTime = 2;
private static int consumeTaskSleepTime = 2000;
private static int produceTaskMaxNumber = 20;

public static void main(String[] args)  throws Exception
{

    //构造一个线程池
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3), new ThreadPoolExecutor.CallerRunsPolicy ());
   

    for(int i=1;i<=produceTaskMaxNumber;i++)
    {
        try
    {
            //产生一个任务,并将其加入到线程池
            String task = "task@ " +i;
    //System.out.println("put " + task);
    ThreadPoolTask a =new ThreadPoolTask(task);
    threadPool.execute(a);
            a= null;
    //便于观察,等待一段时间
    //Thread.sleep(1);
    }
    catch (Exception e)
    {
System.out.println("error-------");
            e.printStackTrace();

      } 
}

    /**
    * 线程池执行的任务
    * @author hdpan
    */
    public static class ThreadPoolTask implements Runnable,Serializable
    {
        private static final long serialVersionUID = 0;
        //保存任务所需要的数据
        private Object threadPoolTaskData;
   
        ThreadPoolTask(Object tasks)
        {
        this.threadPoolTaskData = tasks;
        }
        public void run()
        {
            System.out.println("start .."+threadPoolTaskData);
            try
            {
                ////便于观察,等待一段时间
                Thread.sleep(1000);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            threadPoolTaskData = null;
        }
        public Object getTask()
        {
            return this.threadPoolTaskData;
        }
    }
}
//1、在命令行下编译上面的java文件,并执行,java TestThreadPool  程序执行完,退出。
//2、把produceTaskMaxNumber 改成2后,再编译执行 java TestThreadPool  程序执行完 不退出
为什么会这样呢,谁帮忙解释下呢,纠结了1天,看了api也没看懂,谢谢
2012年7月30日 14:48
目前还没有答案

相关推荐

Global site tag (gtag.js) - Google Analytics