public class Resource { String name; String sex; boolean flag = false; int x = 0; public synchronized void set(String name, String sex){ while (flag) try{ this.wait(); }catch(InterruptedException e){} this.name = name; this.sex = sex; flag = true; this.notifyAll(); x = (x+1)%2; } public synchronized void out(){ while (!flag) try{ this.wait(); }catch(InterruptedException e){} System.out.println(name+"...."+sex); flag = false; this.notifyAll(); } } ----------------------------------------------------------------------------------------- public class Input implements Runnable { Resource r; int x = 0; Input(Resource r){ this.r = r; } @Override public void run() { while (true){ if (r.x == 0) r.set("mike", "man"); else r.set("丽丽", "女女女女女女女女"); } } } -------------------------------- public class Output implements Runnable { Resource r; Output(Resource r) { this.r = r; } @Override public void run() { while(true) { r.out(); } } } ---------------------- public class ResourceDemo { public static void main(String[] args) { Resource r = new Resource(); Input in = new Input(r); Output out = new Output(r); Thread t1 = new Thread(in); Thread t3 = new Thread(in); Thread t5 = new Thread(in); Thread t6 = new Thread(in); Thread t7 = new Thread(in); Thread t8 = new Thread(in); Thread t9 = new Thread(in); Thread t10 = new Thread(in); Thread t11 = new Thread(in); Thread t12 = new Thread(in); Thread t2 = new Thread(out); Thread t4 = new Thread(out); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); t8.start(); t9.start(); t10.start(); t11.start(); t12.start(); } }
运行结果:
为什么会出现这种 重复出现丽丽 又重复出现Mike 的现象呢? 求大神分析一下
我要变大神大神大大神
我要变大神大神大大神
杜牧之
相关分类