本帖最后由 杨兴庭 于 2013-7-30 23:09 编辑
线程问题!这个代码,编译时没有问题,为什么在运行时什么都没有?求解释
class resource
{
private String name;
private boolean flag=false;
private int counnt=1;
public synchronized void set(String name)
{
while (flag)
{
try
{
this.wait();
}
catch (Exception e)
{
throw new RuntimeException("线程等待");
}
this.name= name+"...."+counnt++;
System.out.println(Thread.currentThread().getName()+".生产.."+this.name);
flag= true;
this.notifyAll();
}
}
public synchronized void get()
{
System.out.println("hhhh");
while(!flag)
{
try
{
this.wait();
}
catch (Exception e)
{
throw new RuntimeException("线程等待");
}
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.get();
}
}
}
class communication
{
public static void main(String[] args)
{
resource r= new resource();
producer pro = new producer(r);
consumer con= new consumer(r);
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();
}
}
|
|