package sync;
import java.util.concurrent.Semaphore;
/**
* 公共数据
*
*/
class Shared {
public static int count;
}
/**
* 递减线程
*
*/
class DecThread implements Runnable {
private Semaphore sem;
private String name;
DecThread(Semaphore sem, String name) {
this.sem = sem;
this.name = name;
new Thread(this).start();
}
@Override
public void run() {
try {
System.out.println(name + ":等待通行证..");
sem.acquire();
System.out.println(name + ":得到通行证");
for (int i = 0; i < 5; i++) {
Shared.count--;
System.out.println(name + ":" + Shared.count);
Thread.sleep(10);
}
sem.release();
System.out.println(name + "释放通行证");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 递加线程
*
*/
class IncThread implements Runnable {
private Semaphore sem;
private String name;
IncThread(Semaphore sem, String name) {
this.sem = sem;
this.name = name;
new Thread(this).start();
}
@Override
public void run() {
try {
System.out.println(name + ":等待通行证..");
sem.acquire();
System.out.println(name + ":得到通行证");
for (int i = 0; i < 5; i++) {
Shared.count++;
System.out.println(name + ":" + Shared.count);
Thread.sleep(10);
}
sem.release();
System.out.println(name + "释放通行证");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 信号量通过一个计数器控制对共享资源的访问
*
*/
public class SemaphoreTest {
public static void main(String[] args) {
// 信号量通过一个计数器控制对共享资源的访问
Semaphore sem = new Semaphore(1);
// 新启线程,传入信号量
new IncThread(sem, "Inc");
new DecThread(sem, "Dec");
}
}
//输出
Inc:等待通行证..
Inc:得到通行证
Dec:等待通行证..
Inc:1
Inc:2
Inc:3
Inc:4
Inc:5
Inc释放通行证
Dec:得到通行证
Dec:4
Dec:3
Dec:2
Dec:1
Dec:0
Dec释放通行证