多线程:生产者消费者模型
1、阻塞队列实现
public class Main {
private static final int capacity=2, ptime=6, ctime=6;
private static BlockingQueue<Integer> storage=new LinkedBlockingQueue<>(capacity);
private static Integer count=0;
static class Producer implements Runnable {
@Override
public void run() {
for (int i = 0; i < ptime; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
//这里上锁是为了保证put和打印是原子的,如果不需要打印,可以不上锁。
synchronized (count) {
storage.put(count);
System.out.println("Producer:" + Thread.currentThread().getName() + " put: " + count++);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
for (int i = 0; i < ctime; i++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
System.out.println("Consumer:" + Thread.currentThread().getName() + " take: " + storage.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new Thread(new Consumer(),"C1").start();
new Thread(new Consumer(),"C2").start();
new Thread(new Producer(),"P1").start();
new Thread(new Producer(),"P2").start();
new Thread(new Producer(),"P3").start();
}
}
2、Synchronized实现
class Storage {
final int storageSize;
private int countNow = 0;
Storage(int storageSize) {
this.storageSize = storageSize;
}
public void produce() {
System.out.print("Producer " + Thread.currentThread().getName());
if (countNow < storageSize) {
countNow++;
System.out.print(" ##SUCCESS##, STORAGE:" + countNow);
} else {
System.out.print(" ##FAILTED:STORAGE FULL##");
}
System.out.println(" Producer==========================");
}
public void consume() {
System.out.print("Consumer " + Thread.currentThread().getName());
if (countNow > 0) {
countNow--;
System.out.println(" ##SUCCESS##, STORAGE:" + countNow);
} else {
System.out.println(" ##FAILTED: STORAGE EMPTY##");
}
}
public int getCount(){
return countNow;
}
}
public class Main {
private static Storage storage;
static class Producer implements Runnable {
@Override
public void run() {
for (int i = 0; i < storage.storageSize; i++) {
synchronized (storage) {
storage.produce();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
static class Consumer implements Runnable {
@Override
public void run() {
for (int i = 0; i < storage.storageSize; i++) {
synchronized (storage) {
storage.consume();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
storage=new Storage(10);
new Thread(new Producer(),"P1").start();
new Thread(new Producer(),"P2").start();
new Thread(new Producer(),"P3").start();
new Thread(new Consumer(),"C1").start();
new Thread(new Consumer(),"C2").start();
}
}
生产者和消费者都对同一仓库对象上锁。