本帖最后由 黄奕豪 于 2012-5-21 06:10 编辑
由于敲着习惯了,打了if就顺着打个else,所以打出问题来了,仔细跟毕老师的代码对比,依瓢画葫芦的,终于能实现了!!可是想不通第30行的代码多了个else怎么就不行!!~~~~~大清早的!!愁啊!!!- /*
- 毕老师基础教程-第12天-3(多线程间通信-代码优化)
- 需求:
- 存储个人信息和打印个人信息的程序,一个线程存信息,一个线程打印信息,存完就打印,打印完就存!
- */
- class Info //共享资源个人信息类
- {
- private String name;
- private String sex;
- private boolean flag = true;
- public synchronized void set(String name,String sex)
- {
- if(!flag)
- {
- try {this.wait();}catch (InterruptedException iex){}
- }
- this.name=name;
- this.sex = sex;
- flag=false;
- this.notify();
- }
- public synchronized void print()
- {
- if(flag)
- {
- try {this.wait();}catch (InterruptedException iex){}
- }
- //为什么我在这里加上了个else打印出来的结果就是无序的呢?注释掉就可以轮流打印了!!想不明白~~~~~
- //else
- System.out.println(name+"-----------"+sex);
- flag = true;
- this.notify();
- }
- }
- //负责输入的类
- class Input implements Runnable
- {
- private Info c;
- public Input(Info c)
- {
- this.c = c;
- }
- public void run()
- {
- int flag=0;
- while(true)
- {
- if(flag==0)
- c.set("wangwu","man");
- else
- c.set("李四","女");
- flag=(flag+1)%2;
- }
-
- }
- }
- //负责打印的类
- class Out implements Runnable
- {
- private Info c;
- public Out(Info c)
- {
- this.c = c;
- }
- public void run()
- {
- while(true)
- {
- c.print();
- }
- }
- }
- class ThreadCommunicationDemo2
- {
- public static void main(String[] args)
- {
- Info c=new Info();
- new Thread(new Input(c)).start();
- new Thread(new Out(c)).start();
- }
- }
复制代码 |