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

Java NIO - Condition

2016-04-10 18:01 351 查看
Condition用来实现对应Object的wati,notify,notifyAll三个方法。

在Condition中用await()替换wait(),用signal()替换notify() ,用signalAll()替换notifyAll(),传统线程之间的通讯Condition都可以实现。如下列子,我们实现一个读写操作,分为读写线程。

package chp3.condition;


import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.Lock;

import java.util.concurrent.locks.ReentrantLock;


public class BufferThread {


final Lock lock = new ReentrantLock();// 锁

final Condition notFull = lock.newCondition();// 写线程条件

final Condition notEmpty = lock.newCondition();// 读线程条件


final Object[] items = new Object[10];// 缓存队列


int putptr/* 写索引 */, takeptr/* 读索引 */, count/* 队列中存在的数据个数 */;


public void put(Object x) throws InterruptedException {

lock.lock();

try {

while (count == items.length) {

notFull.await();// 阻塞写线程

}

System.out.println("写入操作: index =  " + putptr + " value = " + x);

items[putptr++] = x;

if (putptr == items.length)

putptr = 0;// 如果写索引写到队列的最后一个位置了,那么置为0

++count;// 个数++

notEmpty.signal();// 唤醒读线程

} finally {

lock.unlock();

}

}


public Object take() throws InterruptedException {

lock.lock();

try {

while (count == 0)

// 如果队列为空

notEmpty.await();// 阻塞读线程

Object x = items[takeptr];// 取值

System.out.println("读取操作: index =" + takeptr + " vale = " + x);

if (++takeptr == items.length)

takeptr = 0;// 如果读索引读到队列的最后一个位置了,那么置为0

--count;// 个数--

notFull.signal();// 唤醒写线程

return x;

} finally {

lock.unlock();

}

}


public static void main(String[] args) {


final BufferThread bt = new BufferThread();


Thread t1 = new Thread(new Runnable() {


@Override

public void run() {

for (int i = 0; i < 250; i++)

	try {

bt.put(i);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});


Thread t2 = new Thread(new Runnable() {


@Override

public void run() {

for (int i = 0; i < 230; i++)

	try {

bt.take();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

});


t1.start();

t2.start();

}

}


参考:http://blog.csdn.net/ghsau/article/details/7481142
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: