java生产者消费者模型,需要考虑多线程安全

方法一:使用synchronized做同步

`

package ProducerConsumer;
import java.util.LinkedList;
import java.util.Queue;
public class ProducerConsumerSynchronized {
private final int MAX_LEN = 100;
private Queue queue = new LinkedList<String>();
class Producer extends Thread {
	
    @Override
    public void run() {
        produce();
    }
    private void produce() {
        while(true) {
            synchronized (queue) {
            	if (queue.size() == MAX_LEN) {
                    System.out.println("队列已经满了,等待消费");
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                queue.add("task");
                queue.notify();
                System.out.println("生产一条任务,当前队列长度为" + queue.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class Consumer extends Thread {
    @Override
    public void run() {
        consumer();
    }
    private void consumer() {
        while (true) {
            synchronized (queue) {
                if (queue.size() == 0) {
                    System.out.println("队列为空,等待生产");
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                queue.poll();
                queue.notify();
                System.out.println("消费者消费一条任务,当前队列长度为" + queue.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public static void main(String[] args) {
    ProducerConsumerSynchronized pc = new ProducerConsumerSynchronized();
//这里也可以使用线程池实现
    Producer producer = pc.new Producer();
    Consumer consumer = pc.new Consumer();
    producer.start();
    consumer.start();
}
}

`

方法二:使用Lock + Condition 实现线程同步
`

package ProducerConsumer;

import java.util.LinkedList;

import java.util.Queue;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class ProducerConsumerLock {

private final int MAX_LEN = 100;
private Queue queue = new LinkedList<String>();
private final Lock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();

class Producer extends Thread {
	
    @Override
    public void run() {
        produce();
    }
    private void produce() {
        while(true) {
        	lock.lock();
        	try {
        		if (queue.size() == MAX_LEN) {
                    	System.out.println("队列已经满了,等待消费");
                    	try {
                    		condition.await();
                    	} catch (InterruptedException e) {
                        		e.printStackTrace();
                    	}
                	}
                queue.add("task");
                condition.signal();
                System.out.println("生产一条任务,当前队列长度为" + queue.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        	}finally {
        		lock.unlock();
        	}
        }
    }
}
class Consumer extends Thread {
    @Override
    public void run() {
        consumer();
    }
    private void consumer() {
        while (true) {
        	lock.lock();
        	try {
        		if (queue.size() == 0) {
                    System.out.println("队列为空,等待生产");
                    try {
                    	condition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                queue.poll();
                condition.signal();
                System.out.println("消费者消费一条任务,当前队列长度为" + queue.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
        	}finally {
        		lock.unlock();
        	}
        }
    }
}
public static void main(String[] args) {
	ProducerConsumerLock pc = new ProducerConsumerLock();
//这里也可以使用线程池实现
    Producer producer = pc.new Producer();
    Consumer consumer = pc.new Consumer();
    producer.start();
    consumer.start();
}
}

`

方法3.使用java concurrent包内置的同步队列实现线程同步,比如LinkedBlockingQueue
`

package ProducerConsumer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class ProducerConsumerConcurentQueue {

private BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
class Producer extends Thread {
        @Override
        public void run() {
            produce();
        }
        private void produce() {
            while(true) {
                try {
                    queue.put(new String("task"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("生产一条任务,当前队列长度为" + queue.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    class Consumer extends Thread {
        @Override
        public void run() {
            consumer();
        }
        private void consumer() {
            while (true) {
                try {
                    queue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者消费一条任务,当前队列长度为" + queue.size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args) {
    	ProducerConsumerConcurentQueue pc = new ProducerConsumerConcurentQueue();
	//这里也可以使用线程池实现
        Producer producer = pc.new Producer();
        Consumer consumer = pc.new Consumer();
        producer.start();
        consumer.start();
    }
   }

`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值