JAVA multi-threaded limiting solve concurrency problems

package concurrent;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Auth: zhouhongliang
 * Date:2019/8/1
 * 并发限流功能
 * Semaphore
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            executorService.execute(() -> {
                try {
                    //semaphore.acquire();//一直等待
                    if (semaphore.tryAcquire(3, TimeUnit.SECONDS)) {//等待3秒
                        play();
                        semaphore.release();
                    } else {
                        System.out.println(Thread.currentThread().getName() + " 进入超时");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
            });
        }
        executorService.shutdown();
    }

    /**
     * 模拟任务
     */
    public static void play() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(new Date()) + " " + Thread.currentThread().getName() + " 进入");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(simpleDateFormat.format(new Date()) + " " + Thread.currentThread().getName() + " 退出");
    }
}

Output Results:
2019-08-01 11:09:50 pool-entered. 1. 1-Thread-
2019-08-01 11:09:50 pool-1-thread- 3 enters
2019-08-01 11:09:50 pool -1-thread-2 enters
2019-08-01 11:09:52 pool-1-thread- 3 exit
2019-08-01 11:09:52 pool-1-thread- 1 exit
2019-08-0111: 09:52 pool-1-thread-2 exit
2019-08-01 11:09:52 pool-1-thread- 4 enter
2019-08-01 11:09:52 pool-1-thread- 5 enters
2019-08 -01 11:09:52 pool-1-thread- 6 into the
pool-1-thread-7 enters timeout
pool-1-thread-8 enters timeout
pool-1-thread-9 into the time-out
pool-1-thread-10 into the timeout
2019-08-01 11:09:54 pool-1-thread- 6 exit
2019-08-01 11:09:54 pool-1-thread- 5 exit
2019-08-01 11:09:54 pool-1 -thread-4 exit

Process finished with exit code 0

Guess you like

Origin blog.51cto.com/11147669/2425542