使用Semaphore控制并发访问

  Semaphore,信号量。

  用在多线程环境下对共享资源访问的一种协调机制。

  当一个线程想要访问共享的资源时,这个线程需要获取Semaphore,如果Semaphore内部计数器的值大于0,Semaphore就会减少内部计数器的值且允许这个线程访问共享资源;

  如果Semaphore内部计数器的值等于0,说明共享资源正在被其他线程访问,就禁止这个线程访问,需等待其他线程释放Semaphore后才能访问。

public class Counter {

    //计数器,共享的资源
public static int count = 0; //声明Semaphore保护共享的资源,任何时候只允许一个线程访问
private static final Semaphore semaphore = new Semaphore(1); public static void add() {
try {
//调用acquire()方法获得semaphore
semaphore.acquire(); System.out.println(Thread.currentThread().getName()+":加1前 count="+count); count++; System.out.println(Thread.currentThread().getName()+":加1后 count="+count); Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//释放semaphore
semaphore.release();
} }
}
public class CounterJob implements Runnable {

    @Override
public void run() {
System.out.println(Thread.currentThread().getName()+":开始执行");
Counter.add();
} }
public class CounterMain {

    /**
* @param args
*/
public static void main(String[] args) { //启动10个线程并发访问
Thread thread[] = new Thread[10];
for (int i = 0; i < 10; i++) {
thread[i] = new Thread(new CounterJob(), "Thread" + i);
} for (int i = 0; i < 10; i++) {
thread[i].start();
}
} }
上一篇:Unity5 AssetBundle


下一篇:OAuth2简易实战(三)-JWT