javaee论坛

普通会员

225649

帖子

65

回复

79

积分

楼主
发表于 2019-11-08 13:23:15 | 查看: 56 | 回复: 1

如果你不懂wait()、notify()怎么使用,最好先复习下我之前的这篇博客,怎么使用wait()、notify()实现生产者和消费者的关系

java之wait()、notify()实现非阻塞的生产者和消费者

二、看下ConditionVariable源代码实现packageandroid.os;/***Classthatimplementstheconditionvariablelockingparadigm.**<p>*Thisdiffersfromthebuilt-injava.lang.Objectwait()andnotify()*inthatthisclasscontainstheconditiontowaitonitself.Thatmeans*open(),close()andblock()aresticky.Ifopen()iscalledbeforeblock(),*block()willnotblock,andinsteadreturnimmediately.**<p>*Thisclassusesitselfastheobjecttowaiton,soifyouwait()*ornotify()onaConditionVariable,theresultsareundefined.*/publicclassConditionVariable{privatevolatilebooleanmCondition;/***CreatetheConditionVariableinthedefaultclosedstate.*/publicConditionVariable(){mCondition=false;}/***CreatetheConditionVariablewiththegivenstate.**<p>*Passtrueforopenedandfalseforclosed.*/publicConditionVariable(booleanstate){mCondition=state;}/***Openthecondition,andreleaseallthreadsthatareblocked.**<p>*Anythreadsthatlaterapproachblock()willnotblockunlessclose()*iscalled.*/publicvoidopen(){synchronized(this){booleanold=mCondition;mCondition=true;if(!old){this.notifyAll();}}}/***Resettheconditiontotheclosedstate.**<p>*Anythreadsthatcallblock()willblockuntilsomeonecallsopen.*/publicvoidclose(){synchronized(this){mCondition=false;}}/***Blockthecurrentthreaduntiltheconditionisopened.**<p>*Iftheconditionisalreadyopened,returnimmediately.*/publicvoidblock(){synchronized(this){while(!mCondition){try{this.wait();}catch(InterruptedExceptione){}}}}/***Blockthecurrentthreaduntiltheconditionisopenedoruntil*timeoutmillisecondshavepassed.**<p>*Iftheconditionisalreadyopened,returnimmediately.**@paramtimeoutthemaximumtimetowaitinmilliseconds.**@returntrueiftheconditionwasopened,falseifthecallreturns*becauseofthetimeout.*/publicbooleanblock(longtimeout){//Object.wait(0)meanswaitforever,tomimicthis,wejust//calltheotherblock()methodinthatcase.Itsimplifies//thiscodeforthecommoncase.if(timeout!=0){synchronized(this){longnow=System.currentTimeMillis();longend=now+timeout;while(!mCondition&&now<end){try{this.wait(end-now);}catch(InterruptedExceptione){}now=System.currentTimeMillis();}returnmCondition;}}else{this.block();returntrue;}}}

三、我们分析怎么使用

 比如有多个线程需要执行同样的代码的时候,我们一般希望当一个线程执行到这里之后,后面的线程在后面排队,然后等之前的线程执行完了再让这个线程执行,我们一般用synchronized实现,但是这里我们也可以用ConditionVariable实现,从源码可以看到,我们初始化可以传递一个boolean类型的参数进去,我们可以传递true进去

publicConditionVariable(booleanstate){mCondition=state;}

然后你看下ConditionVariable类里面这个方法

publicvoidblock(){synchronized(this){while(!mCondition){try{this.wait();}catch(InterruptedExceptione){}}}}

如果第一次初始化的时候mCondition是true,那么第一次调用这里就不会走到wait函数,然后我们应该需要一个开关让mCondition变成false,让第二个线程进来的时候我们应该让线程执行wait()方法,阻塞在这里,这不看下ConditionVariable类里面这个函数

publicvoidclose(){synchronized(this){mCondition=false;}}

这不恰好是我们需要的,我们可以马上调用这个函数close(),然后让程序执行我们想执行的代码,最后要记得调用open方法,如下

publicvoidopen(){synchronized(this){booleanold=mCondition;mCondition=true;if(!old){this.notifyAll();}}}因为这里调用了notifyAll方法,把之前需要等待的线程呼唤醒

所以我们使用可以这样使用

1、初始化

ConditionVariablemLock=newConditionVariable(true);

2、同步的地方这样使用

mLock.block();mLock.close();/**你的代码**/mLock.open();

四、测试代码分析

我先给出一个原始Demo

publicclassMainActivityextendsActionBarActivity{publicstaticfinalStringTAG="ConditionVariable_Test";@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);for(inti=0;i<10;i++){newMythread(""+i).start();}}publicintnum=5;classMythreadextendsThread{Stringname;publicMythread(Stringname){this.name=name;}@Overridepublicvoidrun(){while(true){try{Thread.sleep(1);}catch(InterruptedExceptione){e.printStackTrace();}num--;if(num>=0)Log.i(TAG,"threadnameis:"+name+"numis:"+num);elsebreak;}}}}

运行的结果是这样的:

ConditionVariable_TestIthreadnameis:0numis:4Ithreadnameis:1numis:3Ithreadnameis:2numis:2Ithreadnameis:3numis:1Ithreadnameis:4numis:0

很明显不是我们想要的结果,因为我想一个线程进来了,需要等到执行完了才让另外一个线程才能进来

我们用ConditionVariable来实现下

packagecom.example.conditionvariable;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;importandroid.os.Bundle;importandroid.os.ConditionVariable;importandroid.support.v7.app.ActionBarActivity;importandroid.util.Log;publicclassMainActivityextendsActionBarActivity{publicstaticfinalStringTAG="ConditionVariable_Test";@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mCondition=newConditionVariable(true);for(inti=0;i<10;i++){newMythread(""+i).start();}}publicintnum=5;classMythreadextendsThread{Stringname;publicMythread(Stringname){this.name=name;}@Overridepublicvoidrun(){mCondition.block();mCondition.close();while(true){try{Thread.sleep(1);}catch(InterruptedExceptione){e.printStackTrace();}num--;if(num>=0)Log.i(TAG,"threadnameis:"+name+"numis:"+num);elsebreak;}mCondition.open();}}}

运行的结果如下

onditionVariable_TestIthreadnameis:0numis:4Ithreadnameis:0numis:3Ithreadnameis:0numis:2Ithreadnameis:0numis:1Ithreadnameis:0numis:0

很明显这是我想要的效果,还有其它办法吗?当然有

我们还可以使用ReentrantLock重入锁,代码修改如下

publicclassMainActivityextendsActionBarActivity{publicstaticfinalStringTAG="ConditionVariable_Test";privateLocklock=newReentrantLock();@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);for(inti=0;i<10;i++){newMythread(""+i).start();}}publicintnum=5;classMythreadextendsThread{Stringname;publicMythread(Stringname){this.name=name;}@Overridepublicvoidrun(){lock.lock();while(true){try{Thread.sleep(1);}catch(InterruptedExceptione){e.printStackTrace();}num--;if(num>=0)Log.i(TAG,"threadnameis:"+name+"numis:"+num);elsebreak;}lock.unlock();}}}

运行的结果如下

onditionVariable_TestIthreadnameis:0numis:4Ithreadnameis:0numis:3Ithreadnameis:0numis:2Ithreadnameis:0numis:1Ithreadnameis:0numis:0

很明显这是我想要的效果,还有其它办法吗?当然有,那就是用synchronized同步块,代码改成如下

packagecom.example.conditionvariable;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;importandroid.os.Bundle;importandroid.os.ConditionVariable;importandroid.support.v7.app.ActionBarActivity;importandroid.util.Log;publicclassMainActivityextendsActionBarActivity{publicstaticfinalStringTAG="ConditionVariable_Test";@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);for(inti=0;i<10;i++){newMythread(""+i).start();}}publicintnum=5;classMythreadextendsThread{Stringname;publicMythread(Stringname){this.name=name;}@Overridepublicvoidrun(){synchronized(MainActivity.class){while(true){try{Thread.sleep(1);}catch(InterruptedExceptione){e.printStackTrace();}num--;if(num>=0)Log.i(TAG,"threadnameis:"+name+"numis:"+num);elsebreak;}}}}}

运行的结果如下

onditionVariable_TestIthreadnameis:0numis:4Ithreadnameis:0numis:3Ithreadnameis:0numis:2Ithreadnameis:0numis:1Ithreadnameis:0numis:0

很明显这是我想要的效果

五、总结

在Android开发里面我们一般实现线程通过可以用ConditionVariable、ReentrantLock(重入锁)、synchronized、阻塞队列(ArrayBlockingQueue、LinkedBlockingQueue)  put(Ee):在队尾添加一个元素,如果队列满则阻塞  size():返回队列中的元素个数  take():移除并返回队头元素,如果队列空则阻塞


普通会员

0

帖子

83

回复

88

积分
沙发
发表于 2019-12-22 03:09:23

还是很厉害的

您需要登录后才可以回帖 登录 | 立即注册

触屏版| 电脑版

技术支持 历史网 V2.0 © 2016-2017