您的位置:首页 > 编程语言 > Java开发

java 线程“生产/消费”模型1

2013-06-01 00:17 435 查看
/*资源类*/
public class ShareValue {
private int total;
public ShareValue(int total){
this.total=total;
}

//生产
void putValue(int value){
total+=value;
}

//消费资源
int getValue(int value){
if(total-value>=0){
total-=value;
}else{
value=total;
total=0;
System.out.println("Empty!");
}

return value;
}

//得到当前的资源值
int getNowTotal(){
return total;
}

}

/*  生产者类 */
class Producer extends Thread {
// 共享的ShareValue对象
ShareValue share;
// 要增加的值
int value;

public Producer(String name, ShareValue share, int value) {
super(name);
this.share = share;
this.value = value;
}

public void run() {
//同步share对象 ,直到当前代码块运行完毕后,share的对象锁才会释放
synchronized (share) {
// 在增加之前获取share的total值
int n = share.getNowTotal();
try {
sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}
share.putValue(value);
// 打印增加之前的total的值n,增加的值value和增加之后total的值
System.out.println(getName() + ",Value:" + n + " Put value:"
+ value + " Total value:" + share.getNowTotal());
}

}
}

/*消费者类*/
class Consumer extends Thread{
//共享的ShareValue对象
ShareValue share;
//要减少的值
int value;
public Consumer(String name,ShareValue share, int value) {
super(name);
this.share = share;
this.value = value;
}
public void run(){
//同步share对象,直到当前代码运行完毕后,share的对象锁才会释放
synchronized (share) {
//在减少之前,获取share对象的total值
int n=share.getNowTotal();
try {
sleep(100);
} catch (InterruptedException e) {
System.out.println(e);
}
share.getValue(value);
//打印减少之前的total的值n,减去的值value和减少之后total的值
System.out.println(getName()+",Value:"+n+" Get value:"+value+" Total value:"+share.getNowTotal());
}

}
}

/*  测试主类 */
public class TestDemo {

public static void main(String[] args) {
ShareValue share=new ShareValue(0);
Producer producer1=new Producer("producer1", share, 100);
Producer producer2=new Producer("producer2",share,200);
Consumer consumer=new Consumer("consumer", share, 50);
producer1.start();
producer2.start();
consumer.start();
}

}
/* 通过对share对象的锁定来达到同步的目的  */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: