多线程 12 java5的Semaphere同步工具

package com.renrenche.thread;

/**

 * 信号灯的测试

 */

public class SemaphoreTest {

    public static void main(String[] args){

        ExecutorService threadPool = Executors.newCachedThreadPool();

        final Semaphore semaphore = new Semaphore(3);

        for(int i=0;i<10;i++){

 

                Runnable runnable=new Runnable(){

                    @Override

                    public void run() {

                        try {

                            semaphore.acquire();

                        }catch (Exception e){

                            e.printStackTrace();

                        }

                        System.out.println("线程"+Thread.currentThread().getName()+"已经进入,当前已经有:"+(3-semaphore.availablePermits())+"个线程!");

                        try {

                            Thread.sleep((long)(Math.random()*10000));

                        } catch (InterruptedException e) {

                            e.printStackTrace();

                        }

                        System.out.println("线程"+Thread.currentThread().getName()+"即将离开");

                        semaphore.release();

                        System.out.println("当前线程"+Thread.currentThread().getName()+"已经离开,当前已经有:"+(3-semaphore.availablePermits())+"个线程!");

                    }

                };

                threadPool.execute(runnable);

        }

        System.out.println("main end");

    }

}

如有疑问,请发邮件:[email protected]


github:??https://github.com/wangrui0/

猜你喜欢

转载自blog.csdn.net/qq_35524586/article/details/84983049