java并发编程信号量semapher-亚博电竞手机版
semapher
信号量也是java中的一个同步器,与countdownlatch和cyclebarrier不同的是,它内部的计数器是递增的,并且在一开始初始化semaphoer时可以指定一个初始值,但是并不需要知道需要同步的线程个数,而是在需要同步的地方调用acquire方法时指定需要同步的线程个数。
我们通过下面一个例子来看一下semapher效果:
import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.semaphor恰卡编程网e; public class semaphoretest { private static semaphore semaphore = new semaphore(0); public static void main(string[] args) throws interruptedexception{ executorservice executorservice = executors.newfixedthreadpool(2); executorservice.submit(new runnable() { @override public void run() { try { system.out.println(thread.currentthread() "over"); semaphore.release(); } catch (exception e) { e.printstacktrace(); } } }); executorservice.submit(new runnable() { @override public void run() { try { system.out.println(thread.currentthread() "over"); semaphore.release(); } catch (exception e) { e.printstacktrace(); } } }); semaphore.acquire(2); system.out.println("all child thread over!"); executorservice.shutdown(); } }
如上代码首先创建了一个信号量实例,构造函数的入参为0,说明当前信号量计数器的值为0。然后,main函数向线程池添加两个线程任务,在每个线程内部调用信号量的acquire方法,传参为2说明调用acquire方法的线程会一直阻塞,知道信号量的技术变为2才会返回。如果构造semaphore时,传递的参数为n,并在m个线程中调用了该信号量的release方法,那么在调用acquire使m个线程同步时传递的参数应该是m n。
下面举例子来模拟cyclibarrier复用的功能,代码如下:
import java.util.concurrent.executorservice; import java.util.concurrent.executors; import java.util.concurrent.semaphore; public class semaphoer { private static semaphore semaphore = new semaphore(0); public static void main(string[] args) throws interruptedexception { executorservice executorservice = executors.newfixedthreadpool(2); executorservice.submit(new runnable() { @override public void run() { http://www.cppcns.com try { system.out.println(thread.currentthread() "a task over"); semaphore.release(); } catch (exception e) { e.printstacktrace(); } } }); executorservice.submit(new runnable() { @override public void run() { try { system.out.println(thread.currentthread() "a task over"); semaphore.release(); } catch (exception e) { e.printstacktrace(); } } }); semaphore.acquire(2); system.out.println("task a is over"); executorservice.submit(new runnable() { @override public void run() { try { system.out.println(thread.currentthread() "b task over"); semaphore.release(); } catch (exception e) { e.printstacktrace(); } } }); executorservice.submit(new runnable() { @override public void run() { try { system.out.println(thread.currentthread() "b task over"); semaphore.release(); } catch (exception e) { e.printstacktrace(); } } }); semaphore.acquire(2); system.out.println("task b is over"); executorservice.shutdown(); } }
如上代码首先将线程a和线程b加入到线程池。主线程执行代码(1)后被阻塞。线程a和线程b调用release
方法后信号量的值变为了2,这时候主线程的aquire方法会在获取到2个信号量后返回(返回后当前信号量值为0)。然后主线程添加线程c和线程d到线程池,之后主线程执行代码(2)后被阻塞(因为主线程要获取2个信号量,而当前信号量个数为0)。当线程c和线程d执行完release 方法后,主线程才返回。从本例子可以看出,semaphore
在某种程度上实现了cyclicbarrier 的复用功能。
到此这篇关于java并发编程信号量semapher的文章就介绍到这了,更多相关java semapher内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!