本帖最后由 王德升 于 2012-7-5 18:21 编辑
第一个问题。
class Test implements Runnable
{
private boolean flag;
Test(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{
synchronized(Lock.locka)
{
System.out.println("if locka");
synchronized(Lock.lockb)
{
System.out.println("if lockb");
}
}
}
else
{
synchronized(Lock.lockb)
{
System.out.println("else lockb");
synchronized(Lock.locka)
{
System.out.println("else lockb");
}
}
}
}
}
class Lock
{
static Lock locka = new Lock();//这里怎么可以加静态呢,这不是个对象吗?静态不是只能修饰成员吗?
static Lock lockb = new Lock();
}
class DeadLockDemo
{
public static void main(String[] args)
{
Thread t1 = new Thread(new Test(true));
Thread t2 = new Thread(new Test(false));
t1.start();
t2.start();
}
}
为什么老毕这里写成这样呢?
static Object locka = new Object();
static Object lockb = new Object();
这个和我那个有什么区别呢?
第二个问题。
/*
class Resource
{
private String name;
private int count = 1;
private boolean flag = false;
/*
Resource(String name)
{
this.name = name+"- -"+count++;
}
*/
public synchronized void set(String name)
{
while(flag)
try{this.wait();}catch(Exception e){}
this.name=name+"............"+count++;
System.out.println(Thread.currentThread().getName()+"........生产者."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out()
{
if(flag)
try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....消费者"+this.name);
flag=false;
this.notifyAll();
}
}
class Producer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("+商品+");
}
}
}
class Consumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
class ProducerConsumerDemo
{
public static void main(String[] args)
{
Resource res = new Resource();
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
Thread t3 = new Thread(pro);
Thread t4 = new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
*/
这里我真的不明白了,首先说先我的思路,Input往里面存对象,首先要判断flag是false,那就往里面存东西,然后存完之后要把标记改为true,
然后Input再来判断的时候一看是true就要wait()了,同时唤醒对方,然后Output一来判断一看是true就往外拉东西,拉完之后就把标记改为false,当再来判断之后
就要没有对象了,然后等待,同时唤醒对方,
public synchronized void set(String name)
{
while(flag)
try{this.wait();}catch(Exception e){}
this.name=name+"............"+count++;
System.out.println(Thread.currentThread().getName()+"........生产者."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out()
{
if(!flag)//我不知道这里为什么要这样判断,这样一来不就是假了了吗,那怎么还往外面拉对象呢?
try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"....消费者"+this.name);
flag=false;
this.notifyAll();
}
请问大神我哪里理解错了???? |