线程模拟生产 消费 模式

package test;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class QueueTest {


public static void main(String[] args) {


final Object lock = new Object();
final LinkedList<String> queue = new LinkedList<>();


int maxSize = 10;


// Thread t2 = new Thread(new cusomer(queue, lock));
// t2.start();
//
// for (int i = 0; i < 20; i++) {
//
// Thread t1 = new Thread(new provider(queue, maxSize, lock, i + ""));
// t1.start();
//
// }

//======================
// final MyQueue testQueue = new MyQueue();
//
// new Thread(new Runnable() {
//
// @Override
// public void run() {
//
// for (int i = 0; i < 20; i++) {
// testQueue.add(i+"");
// }
// }
//
// }).start();
//
// new Thread(new Runnable() {
//
// @Override
// public void run() {
//
// for (int i = 0; i < 20; i++) {
// testQueue.get();
// }
// }
//
// }).start();

//=====================

ExecutorService service = Executors.newCachedThreadPool();
//ExecutorService service = Executors.newFixedThreadPool(21);
for (int i = 0; i < 20; i++) {
service.submit(new provider(queue, maxSize, lock, i + ""));
}

for (int i = 0; i < 20; i++) {
service.submit(new cusomer(queue, lock));
}

service.shutdown();



}


}


class provider implements Runnable {


private LinkedList<String> queue;


private int maxSize;


private String item;


private Object lock;


public provider(LinkedList<String> queue, int maxSize, Object lock, String item) {
this.queue = queue;
this.maxSize = maxSize;
this.lock = lock;
this.item = item;
}


@Override
public void run() {


synchronized (lock) {


try {


while (queue.size() >= maxSize) {
lock.wait();
}


queue.add(item);
System.out.println("加入元素 : " + item);
lock.notify();

} catch (Exception e) {
e.printStackTrace();
}


}


}


}


class cusomer implements Runnable {


private LinkedList<String> queue;


private Object lock;


public cusomer(LinkedList<String> queue, Object lock) {
this.queue = queue;
this.lock = lock;
}


@Override
public void run() {


synchronized (lock) {


try {

while(true) {

while (queue.isEmpty()) {
lock.wait();
}

System.out.println("取出元素 : " + queue.removeFirst());
lock.notify();

}


} catch (Exception e) {
e.printStackTrace();
}


}


}


}




class MyQueue {

Object lock = new Object();

private LinkedList<String> queue = new LinkedList<>();

int maxSize =10;

public void add(String item) {

synchronized (lock) {

try {

while(queue.size()>=maxSize) {
lock.wait();
}

queue.add(item);
System.out.println("加入元素 : " + item);
lock.notify();

} catch (Exception e) {
e.printStackTrace();
}

}

}

public void get() {

synchronized (lock) {

try {

while(queue.isEmpty()) {
lock.wait();
}

System.out.println("取出元素 : " + queue.removeFirst());
lock.notify();

} catch (Exception e) {
e.printStackTrace();
}

}

}

}

猜你喜欢

转载自blog.csdn.net/weixin_38783189/article/details/78967919