java多线程操作之Semaphore用法

加入开源中国的第一篇博客!
最近在学习和巩固javaSE的相关基础知识,对多线程同步的Semaphore方法总结用例如下:


package javasedemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 *
 * @author htc
 */
public class JavaSEDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // 线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        
        // 只能个线程同时访问
        final Semaphore semph = new Semaphore(3);
        // 模拟个客户端访问
        for (int index = 1; index < 10; index++) {
            final int NO = index;
            Runnable ru = new Runnable() {
                public void run() {
                    try {
                        // 获取许可
                        semph.acquire();
                        System.out.println("accessing: " + NO);

                        Thread.sleep((long) (Math.random() * 1000));
                        // 访问完后,释放
                        System.out.println("release: " + NO);
                        semph.release();
                    } catch (InterruptedException e) {
                    }
                }
            };
            exec.execute(ru);
        }
        // 退出线程池
        exec.shutdown();
    }

}

run:

accessing: 1

accessing: 2

accessing: 3

release: 3

accessing: 6

release: 2

accessing: 4

release: 4

accessing: 5

release: 1

accessing: 7

release: 7

accessing: 8

release: 5

accessing: 9

release: 6

release: 8

release: 9

成功构建 (总时间: 2 秒)


你可能感兴趣的:(java,thread,多线程,线程,信号量)