`
knight_black_bob
  • 浏览: 822918 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ReentrantLock,Condition

阅读更多

 

 

 

public class ReentrantLockAndConditionTest {

    public static void main(String[] args) {
    	ReentrantLockQueue queue =new  ReentrantLockQueue();
    	for (int i = 0; i < 100; i++) {
			queue.put("a");
			String string = queue.getString();
			System.out.println(string); 
		}
    	
	}


    public abstract class MessageQueue<T>{
    	private Queue<T> queue;
    	private List<FailedMessageWrap> resendList;
    	protected int resendSleepInterval = 1000 * 60 ;
    	protected int maxFailedCount = 10;
    	private Lock sendLock = new ReentrantLock();
    	private Condition sendCondition = sendLock.newCondition();
    	private Lock resendLock = new ReentrantLock();
    	private volatile boolean stopRequired ;
    	 
    	public MessageQueue(){ 
    		queue = new LinkedList<T>(); 
    		resendList = new LinkedList<FailedMessageWrap>(); 
    		stopRequired = false;
    		 
    		ExecutorService sendService = Executors.newFixedThreadPool(1);
    		for (int i = 0; i < 1; i++) {
    			sendService.execute(new SendTask());
    		} 
    		Executors.newSingleThreadExecutor().execute(new ResendTask());
    	}
    	 
    	public void send(T message){
    		if(message == null){
    			return;
    		}
    		
    		try {
    			sendLock.lock(); 
    			queue.add(message); 
    			sendCondition.signalAll();
    		}finally{
    			sendLock.unlock();
    		}
    		
    	}
    	 
    	public void stop(){
    		stopRequired = true;
    	}
    	 
    	protected abstract boolean doSend(T message);
    	 
    	class FailedMessageWrap{
    		private T message;
    		private int failedCount;
    		
    		FailedMessageWrap(T message){
    			this.message = message;
    			failedCount = 0;
    		}

    		public int getFailedCount() {
    			return failedCount;
    		}
     
    		public void increaseFailedCount() {
    			this.failedCount += 1;
    		}

    		public T getMessage() {
    			return message;
    		}
    		
    	}
     
    	class SendTask implements Runnable{
    		@Override
    		public void run() {
    			while(!stopRequired){
    				T message;
    				
    				try {
    					sendLock.lock(); 
    					message = queue.poll();
    					if(message == null){
    						try {
    							sendCondition.await();
    						} catch (Exception e) {
    							e.printStackTrace();
    						}
    						continue;
    					}
    				}finally{
    					sendLock.unlock();
    				}
    					
    				if(!doSend(message)){
    					try {
    						resendLock.lock(); 
    						resendList.add(new FailedMessageWrap(message));
    					} finally{
    						resendLock.unlock();
    					}
    				}
    			
    			}
    			
    		}
    	}
    	 
    	class ResendTask implements Runnable{
    		@Override
    		public void run() { 
    			while(!stopRequired){
    				
    				try {
    					Thread.sleep(resendSleepInterval);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				} 
    				List<FailedMessageWrap> removeList = new ArrayList<FailedMessageWrap>();
    				
    				try {
    					resendLock.lock();
    					 
    					for(FailedMessageWrap messageWrap : resendList){
    						if(messageWrap.getFailedCount() > maxFailedCount){
    							removeList.add(messageWrap);
    							continue;
    						}
    						
    						T message =  messageWrap.getMessage(); 
    						if(!doSend(message)){
    							messageWrap.increaseFailedCount();
    						}else{
    							removeList.add(messageWrap);
    						}
    					}
    				 
    					for (FailedMessageWrap messageWrap : removeList) {
    						resendList.remove(messageWrap);
    					}
    				} finally{
    					resendLock.unlock();
    				}
    			
    			}
    		}
    	}
    	

    }
    
    
	
    public static class ReentrantLockQueue{
    	private ReentrantLock  lock = new ReentrantLock();
    	private Queue<String> queue = new LinkedList<String>(); 
    	public  void put(String s){
    		try{
	    		lock.lock();
	    		queue.add(s);
    		}catch(Exception e){
    			
    		}finally{
    			lock.unlock();
    		}
    	}
    	
    	public String getString(){
    		try{
    			lock.lock();
        		String poll = queue.poll();
        		return poll;
    		}catch(Exception e){
    			
    		}finally{
    			lock.unlock();
    		}
			return null;
    	}
    	
    }
	
    
    
	
	

}

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者 

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(支持支付宝和微信 以及扣扣群),没钱捧个人场,谢谢各位。

 

个人主页http://knight-black-bob.iteye.com/



 
 
 谢谢您的赞助,我会做的更好!

分享到:
评论

相关推荐

    Java多线程之ReentrantLock与Condition - 平凡希 - 博客园1

    1、ReentrantLock简介 2、ReentrantLock函数列表 3、重入的实现 4、公平锁与非公平锁 5、ReentrantLock 扩展的功能 6

    CyclicBarrier,reentrantlock,condition模拟抢票

    用CyclicBarrier,reentrantlock,condition来完成同时购买,同步购买的功能 JUC系列之模拟抢票(N人同时抢票,票不足系统补仓,N-M人继续抢票) http://blog.csdn.net/crazyzxljing0621/article/details/77891620

    java ReentrantLock详解.docx

    ReentrantLock java除了使用关键字synchronized外,还可以使用ReentrantLock实现独占锁的功能。而且ReentrantLock相比synchronized而言功能更加丰富,使用起来更为灵活,也更适合复杂的并发场景。这篇文章主要是从...

    Java多线程中ReentrantLock与Condition详解

    主要介绍了Java多线程中ReentrantLock与Condition详解,需要的朋友可以参考下

    java多线程系列(四)ReentrantLock的使用.docx

    ReentrantLock类可以唤醒指定条件的线程,而object的唤醒是随机的 Condition类和Object类 Condition类的awiat方法和Object类的wait方法等效 Condition类的signal方法和Object类的notify方法等效 Condition类...

    java8源码-java8-source:java8

    java8 源码 java8源码+注释 AbstractQueuedSynchronizer ReentrantLock Condition CountDownLatch Semaphore

    Java中的ReentrantLock类最全讲义

    ReentrantLock的基本用法 2.1 创建ReentrantLock 2.2 获取锁和释放锁 公平性与非公平性 3.1 公平锁 3.2 非公平锁 中断响应 条件变量与Condition 5.1 创建Condition 5.2 await()和signal() 可重入性 ReentrantLock与...

    JUC知识点总结(三)ReentrantLock与ReentrantReadWriteLock源码解析

    8. Lock接口 (ReentrantLock 可重入锁) 特性 ReentantLock 继承接口 Lock 并实现了接口中定义的方法, 它是一种可重入锁, 除了能完成 synchronized 所能完成的所有工作外,还提供了诸如可响应中断锁、可轮询锁...

    JavaLock与Condition的理解Reentran

    JavaLock与Condition的理解ReentrantLock锁的简单使用技巧共5页.pdf.zip

    python使用threading.Condition交替打印两个字符

    threading.Condition默认情况下会通过持有一个ReentrantLock来协调线程之间的工作,所谓可重入锁,是只一个可以由一个线程递归获取的锁,此锁对象会维护当前锁的所有者(线程)和当前所有者递归获取锁的次数(本文在...

    Java并发编程基础.pdf

    线程同步与通信:掌握Java中的同步机制,如synchronized关键字、wait()和notify()方法,以及更高级的并发工具如ReentrantLock、Condition等。了解线程间的通信方式,如共享内存、消息传递等。 并发集合:熟悉Java...

    locks框架:接口.pdf

    Condition 条件变量: 介绍 Lock 接口中的 Condition,它可以实现更复杂的线程等待和通知机制。解释如何使用 await、signal 和 signalAll 方法。 通过这份资源,您将获得关于 Locks 框架中 Lock 接口的深入理解,从...

    Java并发编程相关技术使用案例

    1、本资源包含并发编程基础知识的使用案例,包括:线程创建、Synchronized和Reentrantlock锁的使用、线程安全问题演示、Condition的应用、CountDownLatch的应用、Cyclicbarrier的应用、Semaphore的应用、线程池的...

    Java并发编程学习笔记

    4、ReentrantLock底层实现和如何使用 5、Condition源码分析 6、ReentrantReadWriteLock底层实现原理 7、并发工具类CountDownLatch 、CyclicBarrier和Semaphore底层实现原理 8、线程池原理和如何使用线程池 9、...

    leetcode下载-study:学习笔记

    ReentrantLock 源码 Condition 源码 ConcurrentHashMap 源码 Java 线程状态 JAVA 数据结构 Queue HashMap HashTable ConcurrentHashMap JAVA IO Go Redis Redis Cluster Redis 持久化方式 Redis

    JDK_seaswalker.tar.gz

    Condition CountDownLatch CyclicBarrier ReadWriteLock ReentrantLock Socket UDP IO FileChannel Buffer URLConnection NIO Process HashMap LinkedHashMap TreeMap ConcurrentHashMap ...

    juc-demo:JUC包下常用工具练习Demo

    juc-demo JUC包下常用工具练习Demo 内容: 1、Semaphore 2、CountDownLatch 3、CyclicBarrier 4、ReentrantLock + Condition实现阻塞队列 Created by @minghui.y.

    javalruleetcode-DatabaseAndSort:秋招常见算法的实现

    ReentrantLock 和 Condition 实现了互斥示例。 2.2: WaitNotifyCase 使用object对象自带的wait和notify方法实现了互斥。 2.3 :BlockingQueueExample 使用LinkedList 实现了带有 阻塞的put 和 take 方法的 阻塞队列...

    Lock锁的底层原理完整版

    此外,Lock接口还有一个带条件的锁——Condition接口的实现类ReentrantLock。这种带条件的锁使得线程可以在一定条件下挂起等待,直到其它线程唤醒它。 在实际使用场景中,例如多个用户同时操作一个银行账户的情况,...

Global site tag (gtag.js) - Google Analytics