java線程--信號量Semaphore

Semaphore 使用個例

public class Test {

    static class SemapDemo implements Runnable {

        Semaphore semaphore = new Semaphore(5);

        @Override
        public void run() {

            try {
                semaphore.acquire();
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getId() + " :done!");
                semaphore.release();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) throws InterruptedException {

        SemapDemo r = new SemapDemo();

        ExecutorService exs = Executors.newFixedThreadPool(20);
        for (int i = 0; i < 20; i++) {
            exs.submit(r);

        }
        exs.shutdown();
    }

}
相關文章
相關標籤/搜索