美文网首页
Semaphore应用

Semaphore应用

作者: sunpy | 来源:发表于2019-02-28 11:30 被阅读3次

    场景

    桥只能允许两个人,多一个人上桥就会落水,所以只能保证桥上的人流量为2人。

    实现

    public class SemaphoreTest {
    
        private static final Semaphore semaphore = new Semaphore(2);
        
        public static void main(String[] args) {
            ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 
                    2, 
                    20, 
                    TimeUnit.SECONDS, 
                    new ArrayBlockingQueue<Runnable>(10));
            
            tpe.allowCoreThreadTimeOut(true);
            
            tpe.execute(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + " 上桥");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            
            tpe.execute(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + " 上桥");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            
            tpe.execute(new Runnable() {
    
                @Override
                public void run() {
                    try {
                        semaphore.release();
                        System.out.println(Thread.currentThread().getName() + " 下桥");
                        
                        semaphore.acquire();
                        System.out.println(Thread.currentThread().getName() + " 上桥");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    

    结果:

    pool-1-thread-1 上桥
    pool-1-thread-2 上桥
    pool-1-thread-1 下桥
    pool-1-thread-1 上桥
    

    相关文章

      网友评论

          本文标题:Semaphore应用

          本文链接:https://www.haomeiwen.com/subject/ockhuqtx.html