JDK5 condition线程通信

来源:互联网 发布:淘宝试衣间在线使用 编辑:程序博客网 时间:2024/05/18 00:48

JDK5之后提供了Lock 和 Condition俩个对象完全可以取代synchronized和wait、notify关键字。

 下面实现一个例子说明线程通信.(主次线程交替运行10次)。

   任务类:

package com.skydream.thread.condition;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class Task {private Lock lock = new ReentrantLock();private Condition condition = lock.newCondition();private boolean flag = true;public void add()  {lock.lock();while(flag){try {condition.await();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}try {for (int i = 0; i < 10; i++) {System.out.println("add方法运行10次,这是第"+i+"次");}flag = true;condition.signal();} finally {lock.unlock();}}public void sub() {lock.lock();while(!flag){  try {condition.await();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}try {for (int i = 0; i < 10; i++) {System.out.println("sub方法运行10次,这是第"+i+"次");}flag = false;condition.signal();} finally {lock.unlock();}}}


 

分支线程:

 

package com.skydream.thread.condition;public class BranchThread implements Runnable {private final Task task;public BranchThread(Task task){this.task = task;}@Overridepublic void run() {while(true){task.sub();}}}


主线程:

package com.skydream.thread.condition;public class MainThread {public static void main(String[] args) {Task objTask = new Task();new Thread(new BranchThread(objTask)).start();while(true){objTask.add();}}}


 

运行结果:

 

运行期间互斥,交替运行。

 

在JDK api中使用其实现了一个阻塞队列:

 

作为一个示例,假定有一个绑定的缓冲区,它支持 puttake 方法。如果试图在空的缓冲区上执行 take 操作,则在某一个项变得可用之前,线程将一直阻塞;如果试图在满的缓冲区上执行 put 操作,则在有空间变得可用之前,线程将一直阻塞。我们喜欢在单独的等待 set 中保存put 线程和 take 线程,这样就可以在缓冲区中的项或空间变得可用时利用最佳规划,一次只通知一个线程。可以使用两个Condition 实例来做到这一点。

class BoundedBuffer {   final Lock lock = new ReentrantLock();   final Condition notFull  = lock.newCondition();    final Condition notEmpty = lock.newCondition();    final Object[] items = new Object[100];   int putptr, takeptr, count;   public void put(Object x) throws InterruptedException {     lock.lock();     try {       while (count == items.length)          notFull.await();       items[putptr] = x;        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];        if (++takeptr == items.length) takeptr = 0;       --count;       notFull.signal();       return x;     } finally {       lock.unlock();     }   }  }


 

原创粉丝点击