多线程的单个生产者/消费者
- package com.cn.test;
- class Person{
- private String name;
- private String gender;
- private boolean flag=false;
- public synchronized void set(String name,String gender){
- if(flag){try{this.wait();}catch(InterruptedException e){e.printStackTrace();}
- this.name=name;this.gender=gender;
- flag=true;
- this.notifyAll();
- }
- }
- public synchronized void get(){
- if(!flag){try{this.wait();}catch(InterruptedException e){e.printStackTrace();}
- System.out.println("姓名"+this.name+"性别"+this.gender);
- flag=false;
- this.notifyAll();
- }
- }
- }
- class Input implements Runnable{
- Person p;
- Input(Person p){this.p=p;}
- public void run() {
- int x=0;//-------------------循环存
- while(true){
- if(x==0){
- p.set("zhangsan", "nan");
- }
- else p.set("XIAOHONG", "NV");
- x=(x+1)%2;
- }
- }
- }
- class Output implements Runnable{
- Person p;
- Output(Person p){this.p=p;}
- public void run() {
- while(true){
- p.get();
- }
- }
- }
- public class MutilpDemo {
- public static void main(String[] args) {
- Person p=new Person();
- Input in=new Input(p);
- Output out=new Output(p);
- Thread t1=new Thread(in);
- Thread t2=new Thread(out);
- t1.start();
- t2.start();
- }
- }
复制代码 |
|