Java多线程——生产者消费者模式

来源:互联网 发布:网络词pc是什么意思啊 编辑:程序博客网 时间:2024/06/02 00:28
生产消费者模式,实现功能:1.生产者和消费者同时运行(多线程)。2.实现生产完一个对象后然后消费者消费,而不是生产者生产到一半时被消费者消费(同步锁synchronized)。3.实现生产者生产一个消费者消费一个,而不是消费者消费同一个产品(Object类的wait方法和notify方法)。

public class Share {//共享数据对象private String name;private String gender;private boolean isEmpty = true;synchronized public void push(String name, String gender){try {if(!isEmpty){this.wait();}this.name = name;Thread.sleep(10);this.gender = gender;isEmpty = false;this.notify();} catch (InterruptedException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}synchronized public void pick(){try {if(isEmpty){this.wait();}Thread.sleep(10);System.out.println(this.name+"------"+this.gender);this.isEmpty = true;this.notify();} catch (InterruptedException e) {// TODO 自动生成的 catch 块e.printStackTrace();}}}public class Producer implements Runnable{private Share share;public Producer(Share share){this.share = share;}@Overridepublic void run() {for(int i = 0;i<50;i++){if(i%2==0){share.push("a", "男");}else{share.push("b", "女");}//try {//Thread.sleep(200);//} catch (InterruptedException e) {//// TODO 自动生成的 catch 块//e.printStackTrace();//}}}}public class Consumer implements Runnable {private Share share;public Consumer(Share share) {super();this.share = share;}@Overridepublic void run() {for(int i = 0;i<50;i++){//try {//Thread.sleep(100);//} catch (InterruptedException e) {//// TODO 自动生成的 catch 块//e.printStackTrace();//}share.pick();//try {//Thread.sleep(100);//} catch (InterruptedException e) {//// TODO 自动生成的 catch 块//e.printStackTrace();//}}}}public class Test1 {public static void main(String[] args) {Share sh = new Share();new Thread(new Producer(sh)).start();new Thread(new Consumer(sh)).start();}}
0 0
原创粉丝点击