java 多线程------条件变量

java 多线程------条件变量_第1张图片



代码如下---------------


package dxm.com.test;


import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class ThreadCondition {



public static void main(String[] args) {

//创建并发访问的账号
MyCount1 mycount=new MyCount1("6552314758965741", 100000);
ExecutorService pool=Executors.newFixedThreadPool(2);
Thread t1=new SaveThread("zhangsan", mycount, 10000);
Thread t2=new SaveThread("lisi", mycount, 36000);
Thread t3=new DrawThread("wangwu", mycount, 20000);
Thread t4=new SaveThread("laoliu", mycount, 10000);
Thread t5=new DrawThread("zhangsan", mycount, 30000);
Thread t6=new DrawThread("wangsi", mycount, 1000);

pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);

pool.shutdown();




}

}




class SaveThread extends Thread{

private String name;
private MyCount1 mycount;
private int x;

SaveThread(String name,MyCount1 mycount,int x){
this.name=name;
this.mycount=mycount;
this.x=x;
}

public void run(){
mycount.saving(x, name);
}


}


//取款线程
class DrawThread extends Thread{
private String name;
private  MyCount1 mycount;
private int x;

DrawThread(String name,MyCount1 mycount,int x){
this.name=name;
this.mycount=mycount;
this.x=x;
}

public void run(){
mycount.drawing(x, name);
}


}


class MyCount1{

private String oid;
private int cash;

private Lock lock=new ReentrantLock();
private Condition _save=lock.newCondition();//存款条件
private Condition _draw=lock.newCondition();//取款条件

MyCount1(String oid,int cash){
this.oid=oid;
this.cash=cash;
}

//存款操作
public void saving(int x,String name){
lock.lock();
if(x>0){
cash+=x;
System.out.println(name+"存款"+x+",当前余额"+cash);
}
_draw.signalAll();//唤醒所有等待
lock.unlock();//释放锁
}

public void drawing(int x,String name){
lock.lock();
try{
if(cash-x<0){
_draw.wait();//阻塞取款操作
}else{
cash-=x;
System.out.println(name+"取款"+x+",当前余额为"+cash);
}
_save.signalAll();//唤醒所有存款操作

}catch(Exception e){
e.printStackTrace();
}finally{
lock.unlock();//释放锁
}
}


}


你可能感兴趣的:(java)