java并发控制(2),synchronized模拟阻塞队列

12 篇文章 0 订阅
本文深入探讨了如何利用Java的synchronized关键字来模拟实现一个阻塞队列。通过详细解释并发控制的概念,文章阐述了在多线程环境下,synchronized在确保线程安全和数据一致性方面的关键作用。通过对队列操作的加锁实现,读者可以理解如何创建高效且安全的并发控制机制。
摘要由CSDN通过智能技术生成

import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicInteger;

import com.sun.org.apache.xerces.internal.parsers.CachingParserPool.SynchronizedGrammarPool;

public class MyQueue {

	private LinkedList<Object> list = new LinkedList<Object>();
	
	private AtomicInteger count = new AtomicInteger(0);
	
	private int minSize = 0;
	
	private int maxSize;
	
	public MyQueue(int size){
		this.maxSize = size;
	}
	
	private final Object lock = new Object();
	
	public void put(Object obj){
		System.out.println("Put .... before lock");;

		synchronized(lock){
			while(count.get() == this.maxSize){			
				try {
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("Put .... after lock");;
			list.add(obj);
			System.out.println("新加入的元素 :"+obj);
			count.incrementAndGet();
			lock.notify();
		}
	}
	
	public Object take(){
		Object reuslt = null;
		System.out.println("Take .... before lock");;
		synchronized(lock){
			while(count.get() == this.minSize){
			  try {
				lock.wait();
			  } catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			  }
			}
			System.out.println("Take .... after lock");;

			reuslt = list.removeFirst();
			 System.out.println("移除的元素:"+reuslt);
			count.decrementAndGet();
			lock.notify();
		}
		return reuslt;
	}
	
	
	public int getSize(){
		return this.count.get();
	}
	
	public static void main(String[] args){
		
		MyQueue myQueue = new MyQueue(5);
		myQueue.put("1");
		myQueue.put("2");
		myQueue.put("3");
		myQueue.put("4");
		myQueue.put("5");
		System.out.println("容器长度: "+myQueue.getSize());
		
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				myQueue.put("6");
				myQueue.put("7");
				
				// TODO Auto-generated method stub
				
			}
		},"t1" );
		t1.start();
		
		
		Thread t2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stubQ
			 Object o =   myQueue.take();	
			 Object o1 =   myQueue.take();
		
			}
		},"t2");
		 
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		t2.start();
		
	}
}

以下代码模拟了阻塞的队列过程



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值