class Store2{ //定义“Store2”类
private int seq; //seq数值表示当前交易的次数
private boolean available=false;
public synchronized int get() { //synchronized标识同步方法,定义get方法——消费者调用
while(available==false) {
try {
wait();
}
catch(InterruptedException e) {}
}
available=false;
notify(); //唤醒
return seq; //返回seq(当前交易次数)的值
}
public synchronized void put(int value) { //定义put方法——生产者调用
while(available==true) {
try {
wait();
}catch(InterruptedException e) {}
}
seq=value;
available=true;
notify();
}
}
class Producer1 extends Thread { //定义生产者线程
private Store2 store;
private int num;
public Producer1(Store2 s,int num) {
store=s;
this.num=num;
}
public void run() {
for(int i=0;i<10;i++) {
store.put(i); //调用store示例里的put方法
System.out.println("Producer #"+this.num+"put:"+i);
try {
sleep((int)(Math.random()*100));
}catch(InterruptedException e) {}
}
}
}
class Comsumer1 extends Thread{ //定义消费者线程
private Store2 store;
private int num;
public Comsumer1(Store2 s,int num) {
store=s;
this.num=num;
}
public void run() {
int value=0;
for(int i=0;i<10;i++) {
value=store.get(); //将seq(当前交易次数)返回赋值给value
System.out.println("Consumer #"+this.num+"got:"+value);
}
}
}
public class 线程锁{
public static void main(String[] args) {
Store2 s=new Store2(); //Store2、Producer1、Comsumer1实例化
Producer1 p2=new Producer1(s,2);
Comsumer1 c2=new Comsumer1(s,2);
p2.start(); //启动p2、c2线程
c2.start();
}
}
JAVA基础——多线程同步实现(生产者/消费者模型)
最新推荐文章于 2021-06-05 18:09:37 发布