溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

JAVA多線程限流解決并發(fā)問題

發(fā)布時間:2020-06-30 08:21:21 來源:網(wǎng)絡(luò) 閱讀:522 作者:戀上程序員 欄目:編程語言
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
 * 并發(fā)限流功能
 * 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();
    }

    /**
     * 模擬任務(wù)
     */
    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() + " 退出");
    }
}

輸出結(jié)果:
2019-08-01 11:09:50 pool-1-thread-1 進入
2019-08-01 11:09:50 pool-1-thread-3 進入
2019-08-01 11:09:50 pool-1-thread-2 進入
2019-08-01 11:09:52 pool-1-thread-3 退出
2019-08-01 11:09:52 pool-1-thread-1 退出
2019-08-01 11:09:52 pool-1-thread-2 退出
2019-08-01 11:09:52 pool-1-thread-4 進入
2019-08-01 11:09:52 pool-1-thread-5 進入
2019-08-01 11:09:52 pool-1-thread-6 進入
pool-1-thread-7 進入超時
pool-1-thread-8 進入超時
pool-1-thread-9 進入超時
pool-1-thread-10 進入超時
2019-08-01 11:09:54 pool-1-thread-6 退出
2019-08-01 11:09:54 pool-1-thread-5 退出
2019-08-01 11:09:54 pool-1-thread-4 退出

Process finished with exit code 0

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI