Java 实现生产者消费者(二)

本文展示了一个使用Java ExecutorService实现的生产者消费者模型示例,该模型包含1个生产者和20个消费者,用于处理任务队列。通过synchronized关键字和wait/notifyAll方法来协调生产者和消费者的同步问题。

今天在论坛里面帮网友写了个,已调试通过1个生成者对应20个消费者,写的比较随意,没单独写类,用的内部类.如果那个地方有错,欢迎大家指正,批评.

public class ExecutorServiceTest {
    
private static int maxTask = 80;
    
private static Object lock = new Object();

    
public static void main(String[] args) {
        
final List tasks = new ArrayList();
        
final ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute(
new Runnable() {
            
public void run() {
                
while (!Thread.interrupted()) {
                    
try {
                        
synchronized (tasks) {
                            
if (tasks.size() == maxTask)
                                tasks.wait();
                        }
                        
synchronized (lock) {
                            
if (tasks.size() != maxTask) {
                                tasks.add(
new Object());
                                System.out.println(
"生产任务");
                                lock.notifyAll();
                                Thread.yield();
                            }
                        }
                    } 
catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        
for (int i = 0; i < 20; i++) {
            exec.execute(
new Runnable() {
                
public void run() {
                    
while (!Thread.interrupted()) {
                        
try {
                            
synchronized (lock) {
                                
if (tasks.size() == 0)
                                    lock.wait();
                            }
                            
synchronized (tasks) {
                                
if (tasks.size() > 0) {
                                    tasks.remove(
0);
                                    System.out.println(
"处理任务");
                                    tasks.notifyAll();
                                }
                            }
                        } 
catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
        exec.shutdown();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值