java多线程:并发包中的信号量和计数栓的编程模型

时间:2022-02-01 10:15:36

一:信号量的编程模型

 package com.yeepay.sxf.test.atomic.test;

 import java.util.concurrent.Semaphore;

 /**
* 测试信号量
* 相当于有一把可以控制并发量的锁。
* 例如银行柜台,只有两个窗口。但三个人做业务,只允许同时有两个人能进行做业务
*
* 多线程
* @author sxf
*
*/
public class TestSemaphore { public static void main(String[] args) {
//声明两个信号量
Semaphore semaphore=new Semaphore(2);
//有三个线程抢许可证(信号量)做业务
Person person1=new Person("sxf", semaphore);
Person person2=new Person("sxs", semaphore);
Person person3=new Person("ssy", semaphore);
//启动这三个线程工作(同时允许的并发量为2)
person1.start();
person2.start();
person3.start();
} } class Person extends Thread{ /**
* 信号量(许可证)
*/
private Semaphore semaphore;
/**
* 当前线程的名字
*/
private String cname; public Person(String cname,Semaphore semaphore) {
this.cname=cname;
this.semaphore=semaphore;
} @Override
public void run() {
System.out.println("Person.run(==>)"+getCname()+" is wating........");
try {
//获取许可证
semaphore.acquire();
System.out.println("Person.run()"+getCname()+" is doneing.......");
Thread.sleep(3000);
System.out.println("Person.run(==>)"+getCname()+" is service done......");
//释放许可证
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
} public Semaphore getSemaphore() {
return semaphore;
} public void setSemaphore(Semaphore semaphore) {
this.semaphore = semaphore;
} public String getCname() {
return cname;
} public void setCname(String cname) {
this.cname = cname;
} }

一:计数栓的编程模型

 package com.yeepay.sxf.test.atomic.test;

 import java.util.concurrent.CountDownLatch;
/**
* 测试记数栓
*
* 当记数栓定义的多个事件发生时候,才能执行任务
* @author sxf
*
*/
public class TestCountDowanLatch { public static void main(String[] args) throws InterruptedException {
//定义三个事件的计数栓
CountDownLatch countDownLatch=new CountDownLatch(3);
//定义任务线程
Runer runer=new Runer("sxf", countDownLatch);
Runer runer2=new Runer("sxs", countDownLatch);
Runer runer3=new Runer("sxy", countDownLatch); //启动任务线程
runer.start();
runer2.start();
runer3.start(); //住线程监控特定事件的发生次数
for(int i=0;i<3;i++){
Thread.sleep(3000);
System.out.println("TestCountDowanLatch.main(事件发生第【"+(i+1)+"】次");
if(i==2){
System.out.println("TestCountDowanLatch.main(事件发生次数已经达标允许线程执行任务)");
countDownLatch.countDown();
} } }
} class Runer extends Thread{
/**
* 计数栓
*/
private CountDownLatch countDownLatch; private String cname; public Runer(String cname,CountDownLatch countDownLatch) {
this.cname=cname;
this.countDownLatch=countDownLatch;
} @Override
public void run() {
try {
System.out.println("Runer.run()"+getName()+" is await.............");
countDownLatch.await();
System.out.println("Runer.run()"+getName()+" is doneing...........cname"); } catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public CountDownLatch getCountDownLatch() {
return countDownLatch;
} public void setCountDownLatch(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
} public String getCname() {
return cname;
} public void setCname(String cname) {
this.cname = cname;
} }