JAVAの並行性の問題を解決する制限マルチスレッド

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() + " 退出");
    }
}

出力結果:
。2019年8月1日11時09分50秒プール-入っ1. 1-スレッド
2019年8月1日11時09分50秒プール-1-スレッド 3が入った
2019年8月1日11時09分50秒プール-1スレッド2が入射
2019年8月1日11時09分52秒プール-1-スレッド 3 出口
2019年8月1日11時09分52秒プール-1-スレッド 1つの出口
2019-08-0111: 9時52分プール-1スレッド2出口
2019年8月1日11時09分52秒プール-1-スレッド 4は、 入力
2019年8月1日は11時09分52秒プール-1-スレッド 5は入射
2019から08を-01 11時09分52秒プール-1-スレッド 6
プール-1スレッド7が入射タイムアウト
プール-1スレッド8がタイムアウトに入る
タイムアウトにプール-1スレッド9
にプール-1スレッド10タイムアウト
2019年8月1日11時09分54秒プール-1-スレッド 6 出口
2019年8月1日11時09分54秒プール-1-スレッド 5 出口
2019年8月1日11時09分54秒プール1 -thread-4出口

プロセス終了コード0で終了

おすすめ

転載: blog.51cto.com/11147669/2425542