美文网首页爱编程,爱生活
java concurrent 之 semaphore

java concurrent 之 semaphore

作者: 熬夜的猫头鹰 | 来源:发表于2018-06-16 21:53 被阅读12次

    java concurrent 之 semaphore

    java.util.concurrent.Exchanger类表示一种会聚点,其中两个线程可以交换对象。 这是一个这个机制的例证

    image

    通过两种exchange()方法之一来完成交换对象。 这是一个例子:

    
    Exchanger exchanger = new Exchanger();
    
    ExchangerRunnable exchangerRunnable1 =
            new ExchangerRunnable(exchanger, "A");
    
    ExchangerRunnable exchangerRunnable2 =
            new ExchangerRunnable(exchanger, "B");
    
    new Thread(exchangerRunnable1).start();
    new Thread(exchangerRunnable2).start();
    
    
    
    public class ExchangerRunnable implements Runnable{
    
        Exchanger exchanger = null;
        Object    object    = null;
    
        public ExchangerRunnable(Exchanger exchanger, Object object) {
            this.exchanger = exchanger;
            this.object = object;
        }
    
        public void run() {
            try {
                Object previous = this.object;
    
                this.object = this.exchanger.exchange(this.object);
    
                System.out.println(
                        Thread.currentThread().getName() +
                        " exchanged " + previous + " for " + this.object
                );
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    输出

    
    Thread-0 exchanged A for B
    Thread-1 exchanged B for A
    
    

    相关文章

      网友评论

        本文标题:java concurrent 之 semaphore

        本文链接:https://www.haomeiwen.com/subject/nkxieftx.html