1.wait及notify方式
class Business{
private boolean bShouldSub =true;
public
synchronized void sub(int i){
while(!bShouldSub){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread equeece of "+j+"***"+i);
}
bShouldSub=false;
this.notify();
};
public
synchronized void main(int i){
while(bShouldSub){//用while
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=0;j<20;j++){
System.out.println("main thread equeece**************"+j+"***"+i);
}
bShouldSub=true;
this.notify();
}
}
2.Condition方式 cclass Business{
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
private boolean bShouldSub =true;
public
/*synchronized */ void sub(int i){
lock.lock();
try{
while(!bShouldSub){
try {
condition.await();
//this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("sub thread equeece of "+j+"***"+i);
}
bShouldSub=false;
condition.signal();
//this.notify();
}finally{
lock.unlock();
}
};
public
/* synchronized */void main(int i){
lock.lock();
try{
while(bShouldSub){//用while
try {
condition.await();
//this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=0;j<20;j++){
System.out.println("main thread equeece**************"+j+"***"+i);
}
bShouldSub=true;
condition.signal();
//this.notify();
}finally{
lock.unlock();
}
}
}
3.condition的条件阻塞 实例
class ConditionArray{
Lock lock=new ReentrantLock();
Condition isFull=lock.newCondition();
Condition isEmpty=lock.newCondition();
Object[] items=new Object[10];
int count,putptr,taketr;
public void put(Object x) throws Exception{
lock.lock();
try {
while(count==items.length){
isFull.await();
}
items[putptr]=x;
if(++putptr==items.length) putptr=0;
count++;
isEmpty.signal();
} finally{
lock.unlock();}
}
public Object get() throws InterruptedException {
lock.lock();
try {
while(count==0){
isEmpty.await();
}
Object x=items[taketr];
if(++taketr==items.length) taketr=0;
--count;
isFull.signal();
return x;
} finally{
lock.unlock();
}
}
}
|
Condition/Object.wait/Object.notify
最新推荐文章于 2021-04-26 15:49:38 发布