标签:dem 操作 通过 赋值 一个 sync out 机制 run
package java14; /** * 2017/10/6 * 说明: */ public class Resource { String name; String sex; }
package java14; /** * 2017/10/6 * 说明: */ public class Input implements Runnable { Resource r ; public Input(Resource r){ this.r = r; } @Override public void run() { int x = 0; while(true){ if(x ==0){ r.name = "张三"; r.sex = "男"; }else{ r.name = "李四"; r.sex = "女"; } x ++; x %= 2; } } }
package java14; /** * 2017/10/6 * 说明: */ public class Output implements Runnable { Resource r ; public Output(Resource r){ this.r = r; } @Override public void run() { while(true){ System.out.println(r.name +":"+r.sex); } } }
package java14; /** * 2017/10/6 * 说明: */ public class ResourceDemo { public static void main(String[] args) { Resource r = new Resource(); Input i = new Input(r); Output o = new Output(r); Thread t1 = new Thread(i); Thread t2 = new Thread(o); t1.start(); t2.start(); } }
package java14; /** * 2017/10/6 * 说明: */ public class Input implements Runnable { Resource r ; public Input(Resource r){ this.r = r; } @Override public void run() { int x = 0; while(true){ synchronized (Object.class){ if(x ==0){ r.name = "张三"; r.sex = "男"; }else{ r.name = "李四"; r.sex = "女"; } } x ++; x %= 2; } } }
package java14; /** * 2017/10/6 * 说明: */ public class Output implements Runnable { Resource r ; public Output(Resource r){ this.r = r; } @Override public void run() { while(true){ synchronized (Object.class){ System.out.println(r.name +":"+r.sex); } } } }
标签:dem 操作 通过 赋值 一个 sync out 机制 run
原文地址:http://www.cnblogs.com/xuweiweiwoaini/p/7631952.html