信号量通过一个计数器控制对共享资源的访问
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();}@Overridepublic 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();}@Overridepublic 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:1Inc:2Inc:3Inc:4Inc:5Inc释放通行证Dec:得到通行证Dec:4Dec:3Dec:2Dec:1Dec:0Dec释放通行证
?