synchronized模式
消费者
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Consumer implements Runnable{
private ArrayBlockingQueue queue;
private String threadName;
@SneakyThrows
@Override
public void run() {
while(true) {
synchronized (queue) {
while (queue.size() == 0) {
System.out.println("队列为空");
queue.wait();
}
System.out.println(threadName + " 消费了:" + queue.take());
queue.notifyAll();
}
}
}
}
生产者
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Producer implements Runnable{
private ArrayBlockingQueue queue;
private String threadName;
@SneakyThrows
@Override
public void run() {
while(true) {
synchronized (queue) {
while (queue.size() == 10) {
System.out.println("队列满了");
queue.wait();
}
int num = (int) Math.round(Math.random() * 10);
System.out.println(threadName + " 生产了: " + num);
queue.add(num);
queue.notifyAll();
Thread.sleep(100);
}
}
}
}
main
public static void main(String[] args) {
ExecutorService pool = new ThreadPoolExecutor(5, 5,
10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()
);
ArrayBlockingQueue queue = new ArrayBlockingQueue(10);
Producer producer1 = new Producer(queue,"producer01");
Producer producer2 = new Producer(queue,"producer02");
Consumer c1 = new Consumer(queue,"consumer01");
Consumer c2 = new Consumer(queue,"consumer02");
pool.submit(producer1);
pool.submit(c1);
pool.submit(producer2);
pool.submit(c2);
}
Lock 模式
public class SyncPandC {
private final int MAX_LEN = 10;
private Queue<Integer> queue = new LinkedList<Integer>();
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
class Producer extends Thread {
@Override
public void run() {
while (true) {
lock.lock();
try {
while (queue.size() == MAX_LEN) {
System.out.println("当前队列满");
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(1);
condition.signalAll();
System.out.println("生产者生产一条任务,当前队列长度为" + queue.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
class Consumer extends Thread {
@Override
public void run() {
while (true) {
lock.lock();
try {
while (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();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
public static void main(String[] args) {
SyncPandC spc = new SyncPandC();
spc.new Producer().start();
spc.new Consumer().start();
}
}