JAVA基础——多线程同步实现(生产者/消费者模型)

来源:互联网 发布:js escape的用法 编辑:程序博客网 时间:2024/05/19 22:46
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(当前交易次数)返回赋值给valueSystem.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();}}

阅读全文
0 0