在某公司一道笔试题,但是想了半天没想出好的解决方案,可能是当时有点紧张,我这个人一到面试就发挥不出来自己的应有的状态,哎,我这是老毛病了!言归正传,题目是这样的:有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; } } }