您的位置:首页 > 编程语言 > Java开发

java实现线程安全的队列

2017-04-06 11:23 274 查看
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类
自带的例子,研读测试一下

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程安全 队列