{ IValueCallback remoteCallback = new IValueCallback.Stub() { <strong><span style="color:#ff0000;">(B)</span></strong> public void onReceiveValue(final Bundle value) throws RemoteException { synchronized (syncObject) { mReturnValue = arg.result; syncObject.notify(); //执行完毕,notify通知代码继续进行 } } }; boolean bSuccess = false; synchronized (syncObject) { <strong><span style="color:#ff0000;">(A) </span></strong>sendRequest(CommandConstant.COMMAND_NAVIGATION_ITEM_EXIST, arg, remoteCallback); try { syncObject.wait(5000); //等待Callback部分执行完毕 } catch (InterruptedException e) { e.printStackTrace(); } } return mReturnValue; }
A
CountDownLatch
is initialized with a given count. The
await
methods block until the current count reaches zero due to invocations of the
countDown()
method, after which all waiting threads are released and any subsequent invocations of
await
return immediately. This is a one-shot phenomenon -- the count cannot be reset.
countDown()
方法)。
你可以向CountDownLatch对象设置一个初始的数字作为计数值,任何调用这个对象上的await()方法都会阻塞,直到这个计数器的计数值被其他的线程减为0为止。
上面的代码修改为:
{ CountDownLatch cdl = new CountDownLatch (2);//2次的计数器 IValueCallback remoteCallback = new IValueCallback.Stub() { (B) public void onReceiveValueA(final Bundle value) throws RemoteException { mReturnValue = arg.result && mReturnValue ; cdl.countDown(); // 减少一次计数 } public void onReceiveValueB(final Bundle value) throws RemoteException { mReturnValue = arg.result&& mReturnValue ; cdl.countDown(); // 减少一次计数 } } }; boolean bSuccess = false; (A) sendRequest(CommandConstant.COMMAND_NAVIGATION_ITEM_EXIST, arg, remoteCallback); try { cdl.await() //等计数器清零后返回结果 } catch (InterruptedException e) { e.printStackTrace(); } return mReturnValue; }
import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; public class LOLGame { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(10, new Runnable() { @Override public void run() { System.out.println("欢迎来到召唤师峡谷!"); } }); for (int i = 0; i < 10; i++) { new Thread(new Player(i, cyclicBarrier)).start(); } } } class Player implements Runnable { private CyclicBarrier cyclicBarrier; private int id; public Player(int id, CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; this.id = id; } @Override public void run() { try { System.out.println("玩家" + id + "正在读进度条..."); cyclicBarrier.await(); System.out.println("玩家" + id + "购买装备..."); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }
用CountDownLatch和CyclicBarrier处理并发线程
原文地址:http://blog.csdn.net/zys871228/article/details/40736691