java实现线程安全的队列

package com.xue.demo.condition例子;

import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Demo {
	public static void main(String[] args) {
		//测试
		final BoundedBuffer boundedBuffer = new BoundedBuffer();
		//放
		for (int i = 0; i < 2; i++) {
			Thread thread = new Thread(new Runnable() {
				public void run() {
					while(true){
						try {
							boundedBuffer.put("你"+new Random().nextInt(100));
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
			thread.start();
		}
		//拿
		for (int i = 0; i < 3; i++) {
			Thread thread2 = new Thread(new Runnable() {
				public void run() {
					while(true){
						try {
							boundedBuffer.take();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			});
			thread2.start();
		}
	}

}
//jdk的队列例子(线程安全队列),ArrayBlockingQueue 类提供了这项功能,因此没有理由去实现这个示例类
class BoundedBuffer {
	//锁
   final Lock lock = new ReentrantLock();
   //没有满--阻塞条件
   final Condition notFull  = lock.newCondition(); 
   //没有空--阻塞条件
   final Condition notEmpty = lock.newCondition(); 
   //队列
   final Object[] items = new Object[3];
   //放到什么位置,从哪个位置取,当前队列中元素数量
   int putptr, takeptr, count;

   public void put(Object x) throws InterruptedException {
     lock.lock();
     try {
       while (count == items.length) 
         notFull.await();
       items[putptr] = x; 
       Thread.sleep(1000);
       System.out.println(Thread.currentThread().getName()+"--放入--"+x+"--到位置--"+putptr);
       if (++putptr == items.length) putptr = 0;
       ++count;
       notEmpty.signal();
     } finally {
       lock.unlock();
     }
   }

   public Object take() throws InterruptedException {
     lock.lock();
     try {
       while (count == 0) 
         notEmpty.await();
       Object x = items[takeptr]; 
       Thread.sleep(1000);
       System.out.println(Thread.currentThread().getName()+"--取出--"+x+"--从位置--"+putptr);
       if (++takeptr == items.length) takeptr = 0;
       --count;
       notFull.signal();
       return x;
     } finally {
       lock.unlock();
     }
   } 
 }
jdk的
Condition类
自带的例子,研读测试一下
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值