ThreadPoolTask​​Executor在可用的活动线程上添加任务

时间:2017-09-07 11:50:17

标签: java multithreading

我正在尝试使用ThreadPoolTask​​Executor异步调用REST服务。我必须为给定的输入异步调用相同的服务。我有一个特定大小的线程池,并且一旦活动线程数小于池大小,就想向服务发送请求。我不知道怎么能这样做。这是示例代码。

public class CallableWrkr implements Callable<Response>{

    public CallableWrkr(Map<String,String> headers,
             String hostName,  Transfer transfer, String name) {
        this.transfer = transfer;
        this.hostName = hostName;
        this.name = name;
    }

    @Override
    public Response call() throws Exception {
        System.out.println(name + 1);
         Thread.sleep((new Random().nextInt(5000)) + 500);
        CoreServicesImpl service = new CoreServicesImpl();
        service.setHost(hostName);

        Response resp = service.process( headers,
                   transfer);
        System.out.println(name + 2);
        return resp;
    }

}

当我有一个转移对象列表时,我想做下面的事情。

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) context.getBean("taskExecutor");

for (;;) {
            int count = taskExecutor.getActiveCount();
            System.out.println("Active Threads : " + count);
            if(count < taskExecutor.getMaxPoolSize())
            {
                CallableWrkr callableTask = new CallableWrkr(headers transfers.get(i), new Integer(threadNumber).toString());
                Future<Response> result = taskExecutor.submit(callableTask);

                futureList.add(result);
            }
            else {
                wait();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 0) {
                taskExecutor.shutdown();
                break;
            }
        }

不确定我是否可以这样做。是否有队列我可以将列表添加到?

感谢。

0 个答案:

没有答案