- package jichu;
- class Res{
- String name ;
- String sex ;
- boolean flag=false;
- }
- class Input implements Runnable{
- private Res r;
- Input(Res r){
- this.r=r;
- }
- public void run(){
- int x=0;
- while (true)
- {
- synchronized (r) {
- if (r.flag) {try {r.wait();} catch (Exception e) {}
- if (x==0) {r.name="mike";r.sex="man";}
- else {
- r.name="lili";
- r.sex="women";
- }
- x=(x+1)%2;
- r.flag=true;
- r.notify();
- }
- }
- }
- }
-
- }
- class Output implements Runnable{
- private Res r;
- Output(Res r)
- {
- this.r=r;
- }
- public void run(){
- while (true){
- synchronized (r) {if(!r.flag)//判断标记
- try {r.wait();
-
- } catch (Exception e) {
- }
- System.out.println(r.name+"......."+r.sex);
- r.flag=false;
- r.notify();
- }
- }
- }
- }
- public class InPutOutPutDemo {
- public static void main (String [] args){
- Res r= new Res ();
- System.out.println("开始了");
- Input in=new Input (r);
- System.out.println("输入线程建立");
- Output out=new Output(r);
- System.out.println("输出线程建立");
- Thread t1=new Thread(in);
- Thread t2=new Thread (out);
- t1.start();
- System.out.println("开启线程1");
- t2.start();
- System.out.println("开启线程2");
- }
- }
复制代码 运行结果如图片所示,明明程序都走了一遍为什么不出我想要的结果?什么原因啊?错哪里了?
|
|