Condition

  Condition用来显式的定义条件变量,必须与显式锁配套使用。一个显式锁可以配套多个Condition,通过显式锁的newCondition方法得到,条件的判断和Condition的阻塞、通知必须在显式锁的保护下进行。下面看一个通过Condition实现信号量流控的例子(原例子在http://www.cnblogs.com/wuxun1997/p/6822868.html第2点):

package com.wulinfeng.concurrent;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SemaphoreOnLock {
    private final Lock lock = new ReentrantLock();
    private final Condition permitAvailable = lock.newCondition(); // 条件变量
    private int permits;
    private AtomicInteger concurrent = new AtomicInteger(0);
    private AtomicInteger count = new AtomicInteger(0);

    public SemaphoreOnLock(int capacity) {
        lock.lock();
        try {
            this.permits = capacity;
        } finally {
            lock.unlock();
        }
    }

    public void acquire() throws InterruptedException {
        lock.lock();
        try {
            while (permits <= 0) {  // 具体条件
                permitAvailable.await();  // 阻塞线程
            }
            --permits;
        } finally {
            lock.unlock();
        }
    }

    public void release() {
        lock.lock();
        try {
            ++permits;
            permitAvailable.signal(); // 唤醒阻塞线程
        } finally {
            lock.unlock();
        }
    }

    public void service(int request, SemaphoreOnLock sem) throws InterruptedException {

        // 获取信号量,并发数+1
        sem.acquire();
        concurrent.incrementAndGet();

        // 总数+1
        count.incrementAndGet();

        try {
            System.out.printf("request is %d, concurrent is %d, total is %d\n", request, concurrent.get(), count.get());
        } finally {
            sem.release(); // 释放信号量
            concurrent.decrementAndGet();  // 并发数-1
        }
    }

    public static void main(String[] args) {
        final SemaphoreOnLock sem = new SemaphoreOnLock(10);
        final ExecutorService es = Executors.newFixedThreadPool(20);
        final Random r = new Random();

        try {
            for (int i = 0; i < 50; i++) {
                es.execute(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            sem.service(r.nextInt(), sem);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } finally {
            es.shutdown();
        }
    }
}

  运行结果:

request is -1778951338, concurrent is 1, total is 1
request is 1075066906, concurrent is 10, total is 10
request is -200837414, concurrent is 9, total is 9
request is -1639190194, concurrent is 10, total is 13
request is 71037621, concurrent is 10, total is 14
request is -585938121, concurrent is 10, total is 15
request is -1900131855, concurrent is 10, total is 16
request is -1116159838, concurrent is 8, total is 8
request is 1258746809, concurrent is 10, total is 18
request is 706480516, concurrent is 10, total is 19
request is 1434452493, concurrent is 10, total is 20
request is -729026036, concurrent is 10, total is 21
request is -779583500, concurrent is 10, total is 22
request is -549833234, concurrent is 10, total is 23
request is 1485006269, concurrent is 10, total is 24
request is 1970523873, concurrent is 10, total is 25
request is 869293408, concurrent is 10, total is 26
request is -1803861924, concurrent is 10, total is 27
request is 1638663365, concurrent is 10, total is 28
request is 1696301910, concurrent is 10, total is 29
request is 399361261, concurrent is 10, total is 30
request is 578417246, concurrent is 10, total is 31
request is -1116143520, concurrent is 10, total is 32
request is -1664615245, concurrent is 10, total is 33
request is 1562712140, concurrent is 10, total is 34
request is -1118179524, concurrent is 7, total is 7
request is 1917249326, concurrent is 10, total is 36
request is -838893383, concurrent is 10, total is 37
request is 1699389705, concurrent is 10, total is 38
request is -994637321, concurrent is 10, total is 39
request is -1774265235, concurrent is 10, total is 40
request is -1954116413, concurrent is 6, total is 6
request is -1406911710, concurrent is 5, total is 5
request is 1128024304, concurrent is 9, total is 42
request is 992412262, concurrent is 4, total is 4
request is -231446201, concurrent is 8, total is 43
request is 2012613692, concurrent is 8, total is 44
request is 1376746080, concurrent is 8, total is 45
request is 2140793768, concurrent is 8, total is 46
request is 2026689142, concurrent is 3, total is 3
request is -279664490, concurrent is 9, total is 49
request is 983193837, concurrent is 2, total is 2
request is -837354594, concurrent is 8, total is 50
request is -294562086, concurrent is 10, total is 48
request is -402585996, concurrent is 9, total is 47
request is 1943809799, concurrent is 10, total is 41
request is 485819205, concurrent is 10, total is 35
request is 835221789, concurrent is 10, total is 17
request is 2089139150, concurrent is 11, total is 12
request is 2097235027, concurrent is 10, total is 11
时间: 2024-10-20 11:09:17

Condition的相关文章

Java并发编程:线程间协作的两种方式:wait、notify、notifyAll和Condition

在前面我们将了很多关于同步的问题,然而在现实中,需要线程之间的协作.比如说最经典的生产者-消费者模型:当队列满时,生产者需要等待队列有空间才能继续往里面放入商品,而在等待的期间内,生产者必须释放对临界资源(即队列)的占用权.因为生产者如果不释放对临界资源的占用权,那么消费者就无法消费队列中的商品,就不会让队列有空间,那么生产者就会一直无限等待下去.因此,一般情况下,当队列满时,会让生产者交出对临界资源的占用权,并进入挂起状态.然后等待消费者消费了商品,然后消费者通知生产者队列有空间了.同样地,当

Java多线程11:ReentrantLock的使用和Condition

ReentrantLock ReentrantLock,一个可重入的互斥锁,它具有与使用synchronized方法和语句所访问的隐式监视器锁相同的一些基本行为和语义,但功能更强大. ReentrantLock基本用法 先来看一下ReentrantLock的基本用法: public class ThreadDomain38 { private Lock lock = new ReentrantLock(); public void testMethod() { try { lock.lock()

Java Condition

在Condition中,用await()替换wait(),用signal()替换notify(),用signalAll()替换notifyAll(),传统线程的通信方式,Condition都可以实现,这里注意,Condition是被绑定到Lock上的,要创建一个Lock的Condition必须用newCondition()方法. class BoundedBuffer { final Lock lock = new ReentrantLock();//锁对象 final Condition no

再谈AbstractQueuedSynchronizer:共享模式与基于Condition的等待/通知机制实现

共享模式acquire实现流程 上文我们讲解了AbstractQueuedSynchronizer独占模式的acquire实现流程,本文趁热打铁继续看一下AbstractQueuedSynchronizer共享模式acquire的实现流程.连续两篇文章的学习,也可以对比独占模式acquire和共享模式acquire的区别,加深对于AbstractQueuedSynchronizer的理解. 先看一下共享模式acquire的实现,方法为acquireShared和acquireSharedInte

接口 Condition

java.util.concurrent.locks 接口 Condition 所有已知实现类: AbstractQueuedLongSynchronizer.ConditionObject, AbstractQueuedSynchronizer.ConditionObject public interface Condition Condition 将 Object 监视器方法(wait.notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使

【Java多线程通信】syncrhoized下wait()/notify()与ReentrantLock下condition的用法比较

转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6556925.html  一:syncrhoized使用同一把锁的多个线程用通信实现执行顺序的调度 我们知道,使用syncrhoized关键字修饰一个代码块.一个方式时,在代码块.方法执行完毕之前是不会释放掉所持有的锁的,在执行期间,其他申请这个锁的线程只能阻塞等待.这些等待的线程被安排在一个等待队列中. 现在,由于某种原因,在当前同步代码块A中需要另一个同步代码块B先执行完,然后A才能继续进行下去.而同步代

java线程condition

子线程先执行一段代码,再主线程再执行一段代码,两个线程都循环执行50遍.用2个condition来实现,一个是子线程的condition,一个是主线程的condition,代码如下: package threadLock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; publ

Java多线程——Lock&amp;Condition

Lock比传统线程模型中的synchronized方式更加面向对象,与生活中的锁类似,锁本身也应该是一个对象.两个线程执行的代码片段要实现同步互斥的效果,它们必须用同一个Lock对象. package java_thread; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockTest { /** * @param args */ pu

java多线程-Condition

Condition 将 Object 监视器方法(wait.notify 和 notifyAll)分解成截然不同的对象,以便通过将这些对象与任意 Lock 实现组合使用,为每个对象提供多个等待 set(wait-set).其中,Lock 替代了 synchronized 方法和语句的使用,Condition 替代了 Object 监视器方法的使用. 先看一个关于Condition使用的简单实例: 1 public class ConditionTest { 2 public static voi

条件阻塞Condition的应用

Condition的功能类似在传统线程技术中的Object.wait和Object.notity的功能. 例子:生产者与消费者 import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.locks.Condition; import java.util.concurrent.lock