Demo shows how the Semaphore class can limit the number of concurrent threads

package com.zcw.demospringsecurity.demo19;

import java.util.concurrent.Semaphore;

/**
 * @ClassName : MyService
 * @Description : Demo展示Semaphore类是如何实现限制线程并发数的
 * @Author : Zhaocunwei
 * @Date: 2020-04-14 14:31
 */
public class MyService {
    private Semaphore  semaphore = new Semaphore(1);//代表同一时间内,最多允许多少个线程同时执行acquire 和release之间的代码

    public void testMethod(){
        try{
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName()
            +"begin timer=" +System.currentTimeMillis());
            Thread.sleep(5000);
            System.out.println(Thread.currentThread().getName()+"end timer="+System.currentTimeMillis());
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyService myService = new MyService();
        ThreadA a = new ThreadA(myService);
        a.setName("a");
        ThreadB b = new ThreadB(myService);
        b.setName("b");
        ThreadC c = new ThreadC(myService);
        c.setName("c");
        a.start();
        b.start();
        c.start();
    }
}

package com.zcw.demospringsecurity.demo19;

/**
 * @ClassName : ThreadA
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-14 14:37
 */
public class ThreadA extends Thread {
    private MyService myService;
    public ThreadA(MyService myService){
        super();
        this.myService = myService;
    }
    @Override
    public void run(){
        myService.testMethod();
    }
}

package com.zcw.demospringsecurity.demo19;

/**
 * @ClassName : ThreadB
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-14 14:39
 */
public class ThreadB extends Thread {
    private MyService myService;

    public ThreadB(MyService myService){
        super();
        this.myService = myService;
    }
    @Override
    public void run(){
        myService.testMethod();
    }
}

package com.zcw.demospringsecurity.demo19;

/**
 * @ClassName : ThreadC
 * @Description :
 * @Author : Zhaocunwei
 * @Date: 2020-04-14 14:41
 */
public class ThreadC extends Thread {
    private MyService  myService;
    public ThreadC(MyService myService){
        super();
        this.myService = myService;
    }
    @Override
    public void run (){
        myService.testMethod();
    }
}

 
operation result:

Insert picture description here

Published 475 original articles · Like 16 · Visits 30,000+

Guess you like

Origin blog.csdn.net/qq_32370913/article/details/105572866