转载:https://blog.csdn.net/xiaojin21cen/article/details/87196937

写在前面

  灵活使用了锁机制,值得借鉴。

一、synchronized 实现

使用了 wait()、notify()和 notifyAll() 方法

package com.aop8.proAndcum;

import java.util.Random;
import java.util.Vector;
import java.util.concurrent.TimeUnit;

public class MyContainer1<T> {
	
	private final Vector<T> sum = new Vector<>();
	private final int MAX = 10; // 最多10个元素

	public synchronized void put(T t) {
		while (sum.size() == MAX) { // while正常情况下和wait()一起使用,
			try {
				System.err.println("产品已满");
				this.wait(); 
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("产品 add");
		sum.add(t);
		this.notifyAll(); // 通知消费者线程进行消费
	}

	public synchronized T get() {
		T t = null;
		while (sum.size() == 0) {
			try {
				System.err.println("缺货");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		t = sum.remove(0);
		this.notifyAll(); // 通知生产者进行生产
		return t;
	}

	public static void main(String[] args) {
		MyContainer1<String> myContainer1 = new MyContainer1<>();
		// 启动消费者线程
		for (int i = 0; i < 4; i++) {
			new Thread(() -> {
				for (int j = 0; j < 5; j++) {
					try {
						TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
					} catch 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
  • 2022-12-23
  • 2021-11-30
  • 2021-11-30
  • 2021-11-30
猜你喜欢
  • 2022-01-25
  • 2021-12-16
  • 2022-12-23
  • 2022-12-23
  • 2021-11-30
  • 2021-11-30
  • 2021-10-03
相关资源
相似解决方案