多线程-等待唤醒+代码优化

风格不统一 提交于 2019-11-27 19:26:05
public class beginning {
      public static void main(String[] args) {
          Res r = new Res();
          new Thread(new Test(r)).start();
          new Thread(new TestDemo(r)).start(); 
      }
 }
class Test implements Runnable
{
    Res r = new Res();
    Test(Res r)
    {
        this.r = r;
    }
    public void run()
    {
        int x = 0;
        while(true)
        {
                if(x==0)
                {
                        r.set("mike....", "nan...");

                }else
                {
                    r.set("里斯+++++","女女女女女+++++");
                }
            x = (x+1)%2;
        }
    }
}
class TestDemo implements Runnable
{
    Res r = new Res();
    TestDemo(Res r)
    {
        this.r = r;
    }
    
    public void run()
    {
        while(true)
        {
            r.out();
        }
    }
}
class Res
{
    private boolean flag = false;
    private String name;
    private String sex;
    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(this.name+"......"+this.sex);
        flag = false;
        this.notify();
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!