首页 > 代码库 > 黑马程序员-学习日记(多线程间的通信)
黑马程序员-学习日记(多线程间的通信)
//将资源封装成对象class Resour{ String name; String gender;}//将线程执行的任务封装成对象class Input implements Runnable{ private Resour r; Input(Resour r) { this.r = r; } public void run() { int x =0; while(true) { if(x==0) { r.name = "Travis"; r.gender = "male"; } else { r.name = "张妙"; r.gender = "女性"; } x = (x+1)%2; } }}class Output implements Runnable{ private Resour r; Output(Resour r) { this.r = r; } public void run() { while(true) { System.out.println(r.name+" "+r.gender); } }}class myLock{ static Object lockA = new Object(); static Object lockB = new Object();} class mlpcDemo { public static void main(String[] args) { Resour r = new Resour(); Input in = new Input(r); Output out = new Output(r); Thread th0 = new Thread(in); Thread th1 = new Thread(out); th0.start(); th1.start(); }}
于是,我们给赋值的代码块加上同步。这里要注意必须明确哪些代码是要同步的。
//将资源封装成对象class Resour{ String name; String gender;}//将线程执行的任务封装成对象class Input implements Runnable{ private Resour r; Object obj = new Object(); Input(Resour r) { this.r = r; } public void run() { int x =0; synchronized(obj) {
while(true) { if(x==0) { r.name = "Travis"; r.gender = "male"; } else { r.name = "张妙"; r.gender = "女性"; } x = (x+1)%2; } } }}class Output implements Runnable{ private Resour r; Output(Resour r) { this.r = r; } public void run() { while(true) { System.out.println(r.name+" "+r.gender); } }}class myLock{ static Object lockA = new Object(); static Object lockB = new Object();} class mlpcDemo { public static void main(String[] args) { Resour r = new Resour(); Input in = new Input(r); Output out = new Output(r); Thread th0 = new Thread(in); Thread th1 = new Thread(out); th0.start(); th1.start(); }}
表面上看,赋值代码块被加上了同步,但运行的结果依然出现了姓名和性别乱搭配的情况。
于是分析原因,定义同步有两个前提,首先Input和Output这两个线程并未使用同一个锁。
其次,仔细观察下列代码:
Thread th0 = new Thread(in);Thread th1 = new Thread(out);
th0.start();
th1.start();
无论Input还是Output都只有一条线程在执行!
黑马程序员-学习日记(多线程间的通信)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。