Java中信号量Semaphore的简单使用
2016-08-15 15:30
483 查看
Java中信号量Semaphore的简单使用;
假设有3个人去银行办事,只有2个柜员,3人同时到达后须有一人等待,等待前两人办完之后再进行
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
Person pA = new Person(semaphore, "A");
pA.start();
Person pB = new Person(semaphore, "B");
pB.start();
Person pC = new Person(semaphore, "C");
pC.start();
}
}
class Person extends Thread {
private Semaphore semaphore;
public Person(Semaphore semaphore, String name) {
setName(name);
this.semaphore = semaphore;
}
public void run() {
System.out.println(getName() + "正在等待");
try {
semaphore.acquire();
System.out.println(getName() + "正在服务");
sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
semaphore.release();
System.out.println(getName() + "完成服务");
}
}
假设有3个人去银行办事,只有2个柜员,3人同时到达后须有一人等待,等待前两人办完之后再进行
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
Person pA = new Person(semaphore, "A");
pA.start();
Person pB = new Person(semaphore, "B");
pB.start();
Person pC = new Person(semaphore, "C");
pC.start();
}
}
class Person extends Thread {
private Semaphore semaphore;
public Person(Semaphore semaphore, String name) {
setName(name);
this.semaphore = semaphore;
}
public void run() {
System.out.println(getName() + "正在等待");
try {
semaphore.acquire();
System.out.println(getName() + "正在服务");
sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
semaphore.release();
System.out.println(getName() + "完成服务");
}
}
相关文章推荐
- java实现:将一个数逆序输出
- java实现:将一个数逆序输出
- java实现:将一个数逆序输出
- java答疑
- java.sql.SQLException: ORA-00604: 递归 SQL 级别 1 出现错误
- Retrofit结合RxJava个人使用经验
- 第一个Java程序
- 第一个Java程序
- 第一个Java程序
- java基础——实现线程串行执行
- Java 面向对象
- Spring+SpringMVC
- Spring中使用Map、Set、List、数组、属性集合的注入方法配置文件
- java基础——串行与并行
- Eclipse编程助手
- Java 面向对象之 继承
- 可见性修饰符
- JavaEE——properties配置文件的编写和解析获取
- Dubbo与Zookeeper、SpringMVC整合和使用(负载均衡、容错)
- java连接MySQL数据库的超强版