标签:
{ 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(); } } }
与晦涩的同步锁相比,计数器的实现会更easy将多线程问题抽象,将精力投入到详细逻辑的严谨性,而非投入精力为可能的死锁和性能消耗而头疼。
版权声明:本文博客原创文章。博客,未经同意,不得转载。
使用CountDownLatch和CyclicBarrier处理并发线程
标签:
原文地址:http://www.cnblogs.com/mengfanrong/p/4603607.html