我说呢,老觉得不对劲,原来synchronized是解决的是互斥而不是同步

王朝java/jsp·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

对于生产者消费者问题的解决办法中,因为synchronized 的意思是同步的,所以我老是一厢情愿地认为synchronized 解决的是多线程对共享资源的同步问题,据此推理wait(),notify()解决的就是互斥问题了;但是怎么看怎么觉得别扭,今天终于发现,原来synchronized 解决的是互斥,wait(),notify()解决的是同步,这样再看生产者消费者的代码就舒服多了:

class Test

{

public static void main(String[] args)

{

Queue q=new Queue();

Producer p=new Producer(q);

Consumer c=new Consumer(q);

p.start();

c.start();

}

}

class Producer extends Thread

{

Queue q;

Producer(Queue q)

{

this.q=q;

}

public void run()

{

for(int i=0;i<10;i++)

{

q.put(i);

System.out.println("Producer put "+i);

}

}

}

class Consumer extends Thread

{

Queue q;

Consumer(Queue q)

{

this.q=q;

}

public void run()

{

while(true)

{

System.out.println("Consumer get "+q.get());

}

}

}

class Queue

{

int value;

boolean bFull=false;

public synchronized void put(int i)

{

if(!bFull)

{

value=i;

bFull=true;

notify();

}

try

{

wait();

}

catch(Exception e)

{

e.printStackTrace();

}

}

public synchronized int get()

{

if(!bFull)

{

try

{

wait();

}

catch(Exception e)

{

e.printStackTrace();

}

}

bFull=false;

notify();

return value;

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航