java中Semaphore和Exchanger的实例代码和讲解

Semaphore

解释

在java的阻塞方法中,有这样一个semaphore类,它可以允许指定的线程数同时运行,超过了指定数,则会阻塞等待获取的线程释放才会继续执行

实例代码

new semaphore(,)第一个参数permits是允许同时执行的数量,第二个参数是boolean类型,true为公平竞争,类似与公平锁。

演示代码

package ReentrantLockLongAdder;

import javax.xml.crypto.Data;
import java.util.concurrent.Semaphore;

/**
 * @program: solution
 * @description: 演示Semaphore的使用方法 类似于信号灯
 * @author: Wang Hai Xin
 * @create: 2022-11-16 17:36
 **/
public class SemaphoreT {

    /*semaphore 类似于信号灯,创建的时候可以指定 permits(允许)的数量
    * 当超过这个数量之后,就会阻塞
    * */
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(2);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("我是第:" + finalI+" time: "+ System.currentTimeMillis());
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();
                }
            }).start();
        }
    }
}

运行结果如下,因为我们设置了semaphore的permits允许数量为2,所以可以看出两个两个时间相近 进入了方法

我是第:1 time: 1668591715626
我是第:0 time: 1668591715626
我是第:2 time: 1668591716639
我是第:3 time: 1668591716639
我是第:4 time: 1668591717646
我是第:5 time: 1668591717646
我是第:6 time: 1668591718647
我是第:7 time: 1668591718647
我是第:8 time: 1668591719658
我是第:9 time: 1668591719658

使用场景和作用

限流!!!

Exchanger线程之间交换数据

作用

用于线程之间交换数据,调用Exchanger方法之后,就会等待其它线程调用Exchanger方法来交换数据。等待这段时间是阻塞的。exchang()方法的参数就是要交换的数据,返回值就是交换回来的数据

实例代码

package ReentrantLockLongAdder;

import java.util.concurrent.Exchanger;

/**
 * @program: solution
 * @description: 演示Exchanger实例代码,用于线程之间交换数据
 * @author: Wang Hai Xin
 * @create: 2022-11-16 17:53
 **/
public class ExchangerT {

    public static void main(String[] args) {
        Exchanger<Integer> exchanger = new Exchanger<>();

        /**/
        new Thread(() -> {
            int  i = 1;
            try {
                /*用来交换值,等待其它线程调用,如果没有其它线程调用,则会阻塞在这里*/
                i = exchanger.exchange(i);
                System.out.println("线程1的输出: "+ i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }).start();

        new Thread(() -> {
            int  i = 2;
            try {
                i = exchanger.exchange(i);
                System.out.println("线程2的输出: "+ i);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }).start();



    }



}

运行结果

线程2的输出: 1
线程1的输出: 2

使用场景和作用

游戏里交换装备

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑白极客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值