黑马程序员技术交流社区
标题:
关于生产者和消费者的问题
[打印本页]
作者:
AndyYuan
时间:
2015-8-16 16:38
标题:
关于生产者和消费者的问题
public class ProducerConsumer {
public static void main(String[] args) {
Resouse account = new Resouse() ;
Producer producer = new Producer(account) ;
Consumer consumer = new Consumer(account);
Thread t1 = new Thread(producer);
Thread t2 = new Thread(producer);
Thread t3 = new Thread(consumer);
Thread t4 = new Thread(consumer);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
class Resouse {
int sum = 0 ;
Boolean flag = false;
synchronized void save(){
if(flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
notifyAll();
flag = true ;
sum++ ;
System.out.println("producer"+sum);
}
}
synchronized void out(){
if(!flag){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
notifyAll();
flag = false ;
System.out.println("consumer<<<"+sum);
}
}
}
class Producer implements Runnable{
Resouse account ;
public Producer(Resouse account ){
this.account = account ;
}
public void run(){
for(int i=0;i<100;i++){
account.save();
}
}
}
class Consumer implements Runnable{
Resouse account ;
public Consumer(Resouse account ){
this.account = account ;
}
public void run(){
for(int i=0;i<100;i++){
account.out();
}
}
}
复制代码
大部分时候结果小于100,有时还大于100.
作者:
巧克黑力
时间:
2015-8-16 17:08
没看懂,为啥要锁两个函数,用lock就好了吗。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2