多线程——消费者与生产者案例

来源:互联网 发布:淘宝公告栏素材 编辑:程序博客网 时间:2024/05/22 20:52

生产者

package producer_consumer;public class producer implements Runnable{private ShareResourse resource = null;producer(ShareResourse resource){this.resource = resource;}@Overridepublic void run() {for(int i = 0; i < 50; i++){if(i% 2 == 0){resource.push("春哥"+ i, "男");}else{resource.push("凤姐"+ i, "女");}}}}
消费者

package producer_consumer;public class Consumer implements Runnable {private ShareResourse resource = null;public Consumer(ShareResourse resource){this.resource = resource;}@Overridepublic void run() {for(int i = 0; i < 50; i++){resource.popup();}}}
资源管理区

package producer_consumer;//共享的资源姓名与性别public class ShareResourse {private String name;private String gender;private boolean isEmpty = true; // 表示共享资源对象是否为空的状态/** * 生产者想共享资源中存储数据 *  * @param name *            姓名 * @param gender *            性别 */synchronized public void push(String name, String gender) {try {while (!isEmpty) { // 当isEmpty为false 不空的时候等着消费者来消费this.wait();//使用同步锁对象来调用,表示当前线程释放同步锁,进入等待池,只能被其他线程唤醒}//----生产开始------this.name = name;Thread.sleep(10);this.gender = gender;//----生产结束------this.notify();//唤醒一个消费者isEmpty = false;//设置资源部位空} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 消费者去除数据 */synchronized public void popup() {try {while(isEmpty){//空了,消费者等待this.wait();}//--------消费开始--------Thread.sleep(10);System.out.println(name + " - " + gender);//--------消费结束---------this.notify();//唤醒一个生产者isEmpty = true;} catch (InterruptedException e) {e.printStackTrace();}}}
运作类:
package producer_consumer;//测试代码public class App {public static void main(String[] args) {ShareResourse resource = new ShareResourse();//启动生产者对象new Thread(new producer(resource)).start();//启动消费者线程new Thread(new Consumer(resource)).start();}}


原创粉丝点击