黑马程序员技术交流社区
标题:
同步锁的问题
[打印本页]
作者:
李彦来
时间:
2014-8-14 11:50
标题:
同步锁的问题
问题在注释处
public class WaitNotify {
public static void main(String[] args) {
Stu s=new Stu();
WriteInfo w=new WriteInfo(s);
ReadInfo r=new ReadInfo(s);
Thread t1=new Thread(w);
Thread t2=new Thread(r);
t1.start();
t2.start();
}
}
class Stu{
String name;
int age;
boolean flag=false;
}
class WriteInfo implements Runnable{
private Stu s;
int num=0;
WriteInfo(Stu s){
this.s=s;
}
public void run() {
while(true){
synchronized(Stu.class){ //为什么换成r就没有问题了???
if(s.flag){
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(num==0){
s.name="李";
s.age=20;
}else{
s.name="li";
s.age=13;
}
num=(num+1)%2;
s.flag=true;
s.notify();
}
}
}
}
class ReadInfo implements Runnable{
private Stu s;
ReadInfo(Stu s){
this.s=s;
}
public void run() {
while(true){
synchronized(Stu.class){ //为什么换成r就没问题了???
if(!s.flag){
try {
s.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(s.name+s.age);
s.flag=false;
s.notify();
}
}
}
}
复制代码
作者:
李彦来
时间:
2014-8-14 12:26
不是r,是Stu的实例 s,糊涂了....
作者:
yqj
时间:
2014-8-14 16:09
因为里面是s.wait()和s.notify();以s对象作为锁的对象,所以同步代码块里以s做锁不会出问题,如果使用Stu.class做锁对象时,直接用Stu.class.wait();、Stu.class.notify();或wait();、notify();就不会有问题了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2