Java线程之Semaphore

线程同步的目的是让在同一时间只有一个线程同时运行,为了保证逻辑上的正确性,不会出现非线程安全问题。

Semaphore是一个线程同步。

以下是使用情况:

1.当你创建的acquire数量大于申请的limits数量的时候,会直接阻塞当前线程。

Semaphore semaphore = new Semaphore(5)

semaphore.acquires(6);

 

2.Semaphore 有公平信号和非公平信号,比如:循环启动线程运行

Thread[] thread = new Thread[4];

使用非公平信号是:Semaphore semaphore = new Semaphore(1, false); 默认时非公平信号

thread-1 启动 //整个过程开始和结束时无需的状态。

thread-3 启动

thread-4 启动

thread-1 结束

thread-2 启动

thread-4 结束

thread-3 结束

thread-2 结束

使用公平信号 Semaphore semaphore = new Semaphore(1, true);

thread-1 启动 //整个过程启动过程无序,但是将所有线程启动,再根据启动的先后顺序进行结束。

thread-3 启动

thread-4 启动

thread-2 启动

thread-1 结束

thread-3 结束

thread-4 结束

thread-2 结束

 

3.semaphore.tryAcquire();是Semaphore提供的无阻塞的方法,我觉得这个方法应该是非常常用的。如果获取到,方法返回true。如果没有获取到,方法返回flase。这个方法可用来访问唯一资源时,如果没有获取到许可可以进行返回错以及释放资源。并且还可以使用

tryAcquire(int permits, long timeout, TimeUnit unit)进行设置超时。

 

Exchanger:是用来进行线程间通讯的一种方式。可以从它的名字上进行看出,它只是进行了两个线程间的数据互换。例如下面这个例子,总共有4个线程,而使用Exchanger会实现数据的两两互换,也就是说,如果执行顺序是A-B-C-D的话,会将A-B, C-D进行互换。

Exchanger<String> exchanger = new Exchanger<>();

MyThreadA myThreadA = new MyThreadA(exchanger);

MyThreadB myThreadB = new MyThreadB(exchanger);

MyThreadC myThreadC = new MyThreadC(exchanger);

MyThreadC myThreadD = new MyThreadC(exchanger);

myThreadA.start();

myThreadB.start();

myThreadC.start();

myThreadD.start();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值