1 class Res 2 { 3 private String name; 4 private String gender; 5 private boolean flag; 6 7 //根据面向对象的原则,把和属性相关的功能写在类中。 8 //存入数据 9 public synchronized void set(String name,String gender) 10 { 11 if(flag) 12 { 13 try{wait();}catch(InterruptedException e){e.printStackTrace();} 14 } 15 this.name = name; 16 this.gender = gender; 17 flag = true; 18 notify(); 19 } 20 21 //输出数据 22 public synchronized void out() 23 { 24 if(!flag) 25 { 26 try{wait();}catch(InterruptedException e){e.printStackTrace();} 27 } 28 System.out.println(name + "....." + gender); 29 flag = false; 30 notify(); 31 } 32 } 33 34 //输入任务 35 class Input implements Runnable 36 { 37 private Res res; 38 public Input(Res res) 39 { 40 this.res = res; 41 } 42 public void run() 43 { 44 int i = 1; 45 while(true) 46 { 47 if(i==1) 48 res.set("猪小明","男"); 49 else 50 res.set("腿腿","女"); 51 i = (++i)%2; 52 } 53 } 54 } 55 56 //输出任务 57 class Output implements Runnable 58 { 59 private Res res; 60 public Output(Res res) 61 { 62 this.res = res; 63 } 64 public void run() 65 { 66 while(true) 67 { 68 res.out(); 69 } 70 } 71 } 72 73 class Demo 74 { 75 public static void main(String[] args) 76 { 77 Res res = new Res(); 78 Input input = new Input(res); 79 Output output = new Output(res); 80 81 new Thread(input).start(); 82 new Thread(output).start(); 83 84 } 85 } 86
时间: 2024-10-06 12:29:00