黑马程序员技术交流社区
标题:
关于多线程通信锁的问题
[打印本页]
作者:
Destiny
时间:
2012-3-17 10:03
标题:
关于多线程通信锁的问题
多线程通信那块 看到毕老师直接把r放进synchronized()里面,有点不明白 ,哪位能给我细说下呢?
class Res
{
String name;
String sex;
boolean flag = false;
}
class Input implements Runnable
{
private Res r ;
Input(Res r)
{
this.r = r;
}
public void run()
{
int x = 0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(Exception e){}
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="丽丽";
r.sex = "女女女女女";
}
x = (x+1)%2;
r.flag = true;
r.notify();
}
}
}
}
class Output implements Runnable
{
private Res r ;
Output(Res r)
{
this.r = r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
try{r.wait();}catch(Exception e){}
System.out.println(r.name+"...."+r.sex);
r.flag = false;
r.notify();
}
}
}
}
class InputOutputDemo
{
public static void main(String[] args)
{
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
复制代码
作者:
于紫洋
时间:
2012-3-17 10:28
因为两个线程需要同一个锁,r只有一个对象。所以就把 r 当锁传进去了
作者:
刘基军
时间:
2012-3-17 10:35
Res r = new Res();
Input in = new Input(r);
Output out = new Output(r);
这边只创建了一个Res对象,然后将这个对象当参数传递给两个类,这两个类实际都是用这一个对象当锁。
作者:
adison
时间:
2012-3-17 11:09
要实现同步,多个线程使用的必须是同一把锁,而同步代码块所需对象是任意的,这里仅仅是为了方便而用"r"作为对象传进来,因为在你代码中"r"是唯一的
作者:
刘元明
时间:
2012-3-17 11:22
一般情况下同步使用的锁都是this,函数需要被对象调用,那么函数都有一个所属对象引用,就是this。
如果都把this放在同步锁的位置,在第一个同步中this指Input,而在第二个同步中this指Output,这样就不满足同步的前提之一:
使用同一个锁。故锁就不能使用this了
为了保证锁的唯一性,你可以使用Res.class,Input.class,Output.class,InputOutputDemo.class 这四个任意一个作为锁,因为它们是唯一的
考虑到该程序中r对象也是唯一的,简便起见就使用r作为锁放在synchronized()里面,也就是说在这里可以作为锁的不止一个,而r是最简单的一个
这样解释希望你明白
作者:
Destiny
时间:
2012-3-17 12:35
刘元明 发表于 2012-3-17 11:22
一般情况下同步使用的锁都是this,函数需要被对象调用,那么函数都有一个所属对象引用,就是this。
如果都 ...
嗯 基本上明白啦 谢谢你哈 很详细
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2