开发手册 欢迎您!
软件开发者资料库

Java并发 - 条件接口

Java并发条件接口 - 从简单和简单的步骤学习Java并发,从基本到高级概念,包括概述,环境设置,主要操作,线程间通信,同步,死锁,ThreadLocal,ThreadLocalRandom,Lock,ReadWriteLock,Condition,AtomicInteger,AtomicLong ,AtomicBoolean,AtomicReference,AtomicIntegerArray,AtomicLongArray,AtomicReferenceArray,Executor,ExecutorService,ScheduledExecutorService,newFixedThreadPool,newCachedThreadPool,newScheduledThreadPool,newSingleThreadExecutor,ThreadPoolExecutor,ScheduledThreadPoolExecutor,Futures and Callables,Fork-Join框架,BlockingQueue,ConcurrentMap,ConcurrentNavigableMap。

java.util.concurrent.locks.Condition接口提供了一个线程暂停执行的能力,直到给定的条件为真. Condition对象必然绑定到Lock并使用newCondition()方法获得.

条件方法

以下是重要的列表Condition类中可用的方法.

Sr.No.方法&说明
1

public void await()

导致当前线程等到信号通知或中断为止.

2

public boolean await(long time,TimeUnit unit)

导致当前线程等到信号通知或中断,或指定的等待时间过去.

3

public long awaitNanos(long nanosTimeout)

导致当前线程等到信号通知或中断,或者指定的等待时间过去.

4

public long awaitUninterruptibly()

导致当前线程等到发出信号为止.

5

public long awaitUntil()

原因当前线程要等到信号通知或中断,或指定的截止日期过去.

6

public void signal()

唤醒一个等待线程.

7

public void signalAll()

唤醒所有等待的线程.

示例


以下TestThread程序演示了Condition接口的这些方法.这里我们使用signal()来通知和await()来挂起线程.

import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class TestThread {   public static void main(String[] args) throws InterruptedException {      ItemQueue itemQueue = new ItemQueue(10);      //Create a producer and a consumer.      Thread producer = new Producer(itemQueue);      Thread consumer = new Consumer(itemQueue);      //Start both threads.      producer.start();      consumer.start();      //Wait for both threads to terminate.      producer.join();      consumer.join();   }   static class ItemQueue {      private Object[] items = null;      private int current = 0;      private int placeIndex = 0;      private int removeIndex = 0;      private final Lock lock;      private final Condition isEmpty;      private final Condition isFull;      public ItemQueue(int capacity) {         this.items = new Object[capacity];         lock = new ReentrantLock();         isEmpty = lock.newCondition();         isFull = lock.newCondition();      }      public void add(Object item) throws InterruptedException {         lock.lock();         while(current >= items.length)            isFull.await();         items[placeIndex] = item;         placeIndex = (placeIndex + 1) % items.length;         ++current;         //Notify the consumer that there is data available.         isEmpty.signal();         lock.unlock();      }      public Object remove() throws InterruptedException {         Object item = null;         lock.lock();         while(current <= 0) {            isEmpty.await();         }         item = items[removeIndex];         removeIndex = (removeIndex + 1) % items.length;         --current;         //Notify the producer that there is space available.         isFull.signal();         lock.unlock();         return item;      }      public boolean isEmpty() {         return (items.length == 0);      }   }   static class Producer extends Thread {      private final ItemQueue queue;            public Producer(ItemQueue queue) {         this.queue = queue;      }      @Override      public void run() {         String[] numbers =            {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};         try {                        for(String number: numbers) {               System.out.println("[Producer]: " + number);            }            queue.add(null);         } catch (InterruptedException ex) {            ex.printStackTrace();         }       }   }   static class Consumer extends Thread {      private final ItemQueue queue;            public Consumer(ItemQueue queue) {         this.queue = queue;      }      @Override      public void run() {                  try {                        do {               Object number = queue.remove();               System.out.println("[Consumer]: " + number);               if(number == null) {                  return;               }            } while(!queue.isEmpty());         } catch (InterruptedException ex) {            ex.printStackTrace();         }      }   }}

这将产生以下结果.

输出

[Producer]: 1[Producer]: 2[Producer]: 3[Producer]: 4[Producer]: 5[Producer]: 6[Producer]: 7[Producer]: 8[Producer]: 9[Producer]: 10[Producer]: 11[Producer]: 12[Consumer]: null