最近遇到的有关线程池和队列的面试题

      在某公司一道笔试题,但是想了半天没想出好的解决方案,可能是当时有点紧张,我这个人一到面试就发挥不出来自己的应有的状态,哎,我这是老毛病了!言归正传,题目是这样的:有A/B/实现了C三个远程方法实现了相同的功能,返回值类型也相同,写程序提供一个方法,同时访问这三个接口,采用最先返回的结果进行返回。

       这道题我想到了用线程池和计数器+Lock,后来发现实现不了,回到家后仔细想了一下,用lock和计数器根本实现不了,用该用阻塞队列来实现主线程等待线程池第一个返回的结果,实现代码如下(如果有更好的办法请大神赐教):

public class TestThread {

    private static int result ;

    static ExecutorService executor = Executors.newFixedThreadPool(3);
    //用阻塞队列来阻塞主线程,这里可以换成linkblockQueue
    final static ArrayBlockingQueue<Future<Integer>> queue = new ArrayBlockingQueue<Future<Integer>>(3);


    public static void  main(String[] args){
        //启动三个线程来同时调用ABC三个方法
        for(int i = 1 ; i < 4 ; i ++ ){
            Future<Integer> future  =  executor.submit(new TestRun(i));
            queue.add(future);
        }
        Future<Integer> intres = null ; 
        while((intres = queue.poll()) == null);

        try {
            System.out.println(intres.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        executor.shutdown();


    }

    //实现ABC中的方法,有返回值,所有实现callable
    public static class TestRun implements Callable<Integer> {

        private int i = 1 ;

        public TestRun(int seed){
            this.i = seed;
        }

        @Override
        public Integer call() {
            try {
                Thread.sleep(i*1000);
                System.out.println(Thread.currentThread().getName()+"-"+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return i;
        }
    }
}




 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值