本帖最后由 JACK...... 于 2013-12-17 11:17 编辑
- class Res
- {
- private String name;
- private String sex;
- private boolean flag=false;
- public synchronized void set(String name,String sex){
- if(flag)
- try{this.wait();}catch(Exception e){}
- this.name=name;
- this.sex=sex;
- flag=true;
- this.notify();
- }
- public synchronized void out(){
- if(!flag)
- try{this.wait();}catch(Exception e){}
- System.out.println(name+"........."+sex);
- flag=false;
- this.notify();
- }
- }
- class Input implements Runnable
- {
- //资源对象
- private Res r;
- //构造函数,传进来一个对象,将引用赋给r
- Input(Res r)
- {
- this.r=r;
- }
- public void run()
- {
- int x=0;
- while(true)
- {
- if(x==0)
- r.set("mike","man");
-
- else
- r.set("丽丽","女");
-
- x=(x+1)%2;
- }
-
- }
-
- }
- class Output implements Runnable
- {
- private Res r;
- Output(Res r){
- this.r=r;
- }
- public void run(){
- while(true){
- r.out();
- }
-
- }
-
- }
- class Duoxc
- {
- public static void main(String[] args){
- Res r=new Res();
- new Thread(new Input(r)).start();
- new Thread(new Output(r)).start();
- }
- }
复制代码
命令行中出错截图:
请问,错误的原因?out方法,没有加同步
要注意哦!!
修改后截图:
|
|