最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java并發(fā)工具類Phaser詳解

 更新時間:2023年11月30日 08:58:44   作者:啊幾  
這篇文章主要介紹了Java并發(fā)工具類Phaser詳解,Phaser(階段協(xié)同器)是一個Java實現(xiàn)的并發(fā)工具類,用于協(xié)調(diào)多個線程的執(zhí)行,它提供了一些方便的方法來管理多個階段的執(zhí)行,可以讓程序員靈活地控制線程的執(zhí)行順序和階段性的執(zhí)行,需要的朋友可以參考下

前言

Phaser(階段協(xié)同器)是一個Java實現(xiàn)的并發(fā)工具類,用于協(xié)調(diào)多個線程的執(zhí)行。

它提供了一些方便的方法來管理多個階段的執(zhí)行,可以讓程序員靈活地控制線程的執(zhí)行順序和階段性的執(zhí)行。

Phaser可以被視為CyclicBarrierCountDownLatch的進化版,它能夠自適應(yīng)地調(diào)整并發(fā)線程數(shù),可以動態(tài)地增加或減少參與線程的數(shù)量。

所以Phaser特別適合使用在重復(fù)執(zhí)行或者重用的情況。

在這里插入圖片描述

常用API

構(gòu)造方法

  • Phaser(): 參與任務(wù)數(shù)0
  • Phaser(int parties) :指定初始參與任務(wù)數(shù)
  • Phaser(Phaser parent) :指定parent階段器, 子對象作為一個整體加入parent對象, 當(dāng)子對象中沒有參與者時,會自動從parent對象解除注冊
  • Phaser(Phaser parent,int parties) : 集合上面兩個方法

增減參與任務(wù)數(shù)方法

  • int register() 增加一個任務(wù)數(shù),返回當(dāng)前階段號。
  • int bulkRegister(int parties) 增加指定任務(wù)個數(shù),返回當(dāng)前階段號。
  • int arriveAndDeregister() 減少一個任務(wù)數(shù),返回當(dāng)前階段號。

到達、等待方法

  • int arrive() 到達(任務(wù)完成),返回當(dāng)前階段號。
  • int arriveAndAwaitAdvance() 到達后等待其他任務(wù)到達,返回到達階段號。
  • int awaitAdvance(int phase) 在指定階段等待(必須是當(dāng)前階段才有效)
  • int awaitAdvanceInterruptibly(int phase) 階段到達觸發(fā)動作
  • int awaitAdvanceInterruptiBly(int phase,long timeout,TimeUnit unit)
  • protected boolean onAdvance(int phase,int registeredParties)類似CyclicBarrier的觸發(fā)命令,通過重寫該方法來增加階段到達動作,該方法返回true將終結(jié)Phaser對象。

Phaser使用

多線程批量處理數(shù)據(jù)

public class PhaserBatchProcessorDemo {

    private final List<String> data;
    private final int batchsize;//一次處理多少數(shù)據(jù)
    private final int threadCount;//處理的線程數(shù)
    private final Phaser phaser;
    private final List<String> processedData;

    public PhaserBatchProcessorDemo(List<String> data,int batchsize,int threadCount){
        this.data = data;
        this.batchsize = batchsize;
        this.threadCount = threadCount;
        this.phaser = new Phaser(1);
        //this.phaser = new Phaser();
        this.processedData = new ArrayList<>();
    }

    public void process() throws InterruptedException {
        for(int i = 0;i<threadCount;i++){
            System.out.println("phaser.register():"+phaser.register());
            new Thread(new BatchProcessor(i)).start();
            Thread.sleep(50);
        }
        phaser.arriveAndDeregister();//主線程執(zhí)行結(jié)束
        System.out.println("結(jié)束");
    }

    private class BatchProcessor implements Runnable{
        private final int threadIndex;
        public BatchProcessor(int threadIndex){this.threadIndex = threadIndex;}

        @Override
        public void run() {
            int index = 0;
            while(true){
                //所有線程都到達這個點之前會阻塞
                System.out.println("線程"+threadIndex+"phaser.arriveAndAwaitAdvance1():");
                phaser.arriveAndAwaitAdvance();

                //從未處理數(shù)據(jù)中找到一個可以處理的批次
                List<String> batch = new ArrayList<>();
                synchronized (data){
                    while (index < data.size()&&batch.size()<batchsize){
                        String d = data.get(index);
                        if(!processedData.contains(d)){
                            batch.add(d);
                            processedData.add(d);
                        }
                        index++;
                    }
                }
                //處理數(shù)據(jù)
                for(String d:batch){
                    System.out.println("線程"+threadIndex+"處理數(shù)據(jù)"+d);
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                //所有數(shù)據(jù)都處理完當(dāng)前批次之前會阻塞
                System.out.println("線程"+threadIndex+"phaser.arriveAndAwaitAdvance2():");
                phaser.arriveAndAwaitAdvance();
                //所有線程都處理完當(dāng)前批次并且未處理數(shù)據(jù)已經(jīng)處理完之前會阻塞
                if(batch.isEmpty()||index >= data.size()){
                    System.out.println("線程"+threadIndex+"phaser.arriveAndDeregister()"+phaser.arriveAndDeregister());
                    break;
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        List<String> data = new ArrayList<>();
        for(int i = 1;i<=15;i++){
            data.add(String.valueOf(i));
        }

        PhaserBatchProcessorDemo processor = new PhaserBatchProcessorDemo(data,4,3);
        processor.process();
    }
}

/**
 * phaser.register():0
 * 線程0phaser.arriveAndAwaitAdvance1():
 * phaser.register():0
 * 線程1phaser.arriveAndAwaitAdvance1():
 * phaser.register():0
 * 線程2phaser.arriveAndAwaitAdvance1():
 * 結(jié)束
 * 線程2處理數(shù)據(jù)9
 * 線程2處理數(shù)據(jù)10
 * 線程1處理數(shù)據(jù)5
 * 線程1處理數(shù)據(jù)6
 * 線程1處理數(shù)據(jù)7
 * 線程1處理數(shù)據(jù)8
 * 線程2處理數(shù)據(jù)11
 * 線程2處理數(shù)據(jù)12
 * 線程0處理數(shù)據(jù)1
 * 線程0處理數(shù)據(jù)2
 * 線程0處理數(shù)據(jù)3
 * 線程0處理數(shù)據(jù)4
 * 線程2phaser.arriveAndAwaitAdvance2():
 * 線程0phaser.arriveAndAwaitAdvance2():
 * 線程1phaser.arriveAndAwaitAdvance2():
 * 線程2phaser.arriveAndAwaitAdvance1():
 * 線程1phaser.arriveAndAwaitAdvance1():
 * 線程0phaser.arriveAndAwaitAdvance1():
 * 線程0處理數(shù)據(jù)13
 * 線程0處理數(shù)據(jù)14
 * 線程0處理數(shù)據(jù)15
 * 線程0phaser.arriveAndAwaitAdvance2():
 * 線程1phaser.arriveAndAwaitAdvance2():
 * 線程2phaser.arriveAndAwaitAdvance2():
 * 線程1phaser.arriveAndDeregister()4
 * 線程2phaser.arriveAndDeregister()4
 * 線程0phaser.arriveAndDeregister()4
 */

這里提出一個問題:為什么要給主線程也注冊呢?如果不給主線程注冊會怎么樣呢?

在這里插入圖片描述

這里就要提及register() 增加任務(wù)數(shù)量和Phaser()初始化定義任務(wù)數(shù)量的區(qū)別

register()有一個需要注意的點是,如果主線程執(zhí)行速度緩慢的話,很有可能在第一個線程已經(jīng)arrive的時候,第二個線程任務(wù)還沒增加,導(dǎo)致第一個線程因為parties只有1,而沒有阻塞等待就進入下一階段了。

如果不給主線程注冊添加任務(wù),運行結(jié)果如下

phaser.register():0
線程0phaser.arriveAndAwaitAdvance1():
線程0處理數(shù)據(jù)1
線程0處理數(shù)據(jù)2
線程0處理數(shù)據(jù)3
線程0處理數(shù)據(jù)4
phaser.register():1
線程1phaser.arriveAndAwaitAdvance1():
phaser.register():1
線程2phaser.arriveAndAwaitAdvance1():
結(jié)束
線程0phaser.arriveAndAwaitAdvance2():
線程0phaser.arriveAndAwaitAdvance1():
線程2處理數(shù)據(jù)5
線程2處理數(shù)據(jù)6
線程2處理數(shù)據(jù)7
線程2處理數(shù)據(jù)8
線程1處理數(shù)據(jù)9
線程1處理數(shù)據(jù)10
線程1處理數(shù)據(jù)11
線程1處理數(shù)據(jù)12
線程2phaser.arriveAndAwaitAdvance2():
線程1phaser.arriveAndAwaitAdvance2():
線程2phaser.arriveAndAwaitAdvance1():
線程1phaser.arriveAndAwaitAdvance1():
線程0處理數(shù)據(jù)13
線程0處理數(shù)據(jù)14
線程0處理數(shù)據(jù)15
線程0phaser.arriveAndAwaitAdvance2():
線程0phaser.arriveAndDeregister()4
線程1phaser.arriveAndAwaitAdvance2():
線程2phaser.arriveAndAwaitAdvance2():
線程2phaser.arriveAndDeregister()5
線程1phaser.arriveAndDeregister()5

而Phaser()初始化就定義了parties,會讓所有線程都必須到達之前都阻塞才能進入下一階段。

給主線程也增加一個任務(wù)的目的就在于此 如果主線程也有任務(wù),就算主線程執(zhí)行緩慢,第一個線程也必須阻塞等待主線程在第一階段之前,把所有線程都start()啟動。

階段性任務(wù):模擬伙伴出游

public class PhaserDemo {
    public static void main(String[] args) {
        final Phaser phaser = new Phaser(){
            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                //參與者數(shù)量,去除主線程
                int persons = registeredParties - 1;
                switch (phase){
                    case 0:
                        System.out.println("大家都到佘山站了,可以出發(fā)去佘山了,人數(shù):"+persons);
                        break;
                    case 1:
                        System.out.println("大家都到佘山了,出發(fā)去爬山,人數(shù):"+persons);
                        break;
                    case 2:
                        System.out.println("大家都到山頂了,開始休息,人數(shù):"+persons);
                        break;

                }
                //判斷是否只剩下一個主線程,如果是,返回true,代表終止
                return registeredParties ==1;
            }
        };

        phaser.register();
        final PersonTask personTask = new PersonTask();
        //3個全程參加的伙伴
        for(int i = 0;i<3;i++){

            phaser.register();
            new Thread(()->{
                try{
                    personTask.step1Task();
                    phaser.arriveAndAwaitAdvance();

                    personTask.step2Task();
                    phaser.arriveAndAwaitAdvance();

                    personTask.step3Task();
                    phaser.arriveAndAwaitAdvance();

                    personTask.step4Task();
                    phaser.arriveAndDeregister();


                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }).start();
        }
        

        //兩個在山腰半路返回
        for(int i = 0;i<2;i++){
            phaser.register();
            new Thread(()->{
                try{
                    personTask.step1Task();
                    phaser.arriveAndAwaitAdvance();

                    personTask.step2Task();
                    phaser.arriveAndAwaitAdvance();

                    personTask.step3Task();
                    System.out.println("伙伴【"+Thread.currentThread().getName()+"】中途山腰返回");
                    phaser.arriveAndDeregister();

                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }).start();
        }

        while (!phaser.isTerminated()) {
            int phase = phaser.arriveAndAwaitAdvance();
            if (phase == 2) {
                //兩個在佘山直接會合
                for(int i = 0;i<2;i++){
                    phaser.register();
                    new Thread(()->{
                        try{
                            System.out.println("伙伴【"+Thread.currentThread().getName()+"】中途加入");

                            personTask.step3Task();
                            phaser.arriveAndAwaitAdvance();

                            personTask.step4Task();
                            phaser.arriveAndDeregister();

                        }catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }).start();
                }
            }
        }
    }

    static final Random random = new Random();

    static class PersonTask{
        public void step1Task() throws InterruptedException {
            String person = "伙伴【"+Thread.currentThread().getName()+"】";
            System.out.println(person+"從家出發(fā)了......");
            Thread.sleep(random.nextInt(5000));
            System.out.println(person+"到達佘山站");
        }

        public void step2Task() throws InterruptedException {
            String person = "伙伴【"+Thread.currentThread().getName()+"】";
            System.out.println(person+"出發(fā)去佘山");
            Thread.sleep(random.nextInt(5000));
            System.out.println(person+"到達佘山");
        }

        public void step3Task() throws InterruptedException {
            String person = "伙伴【"+Thread.currentThread().getName()+"】";
            System.out.println(person+"出發(fā)去爬山");
            Thread.sleep(random.nextInt(5000));
            System.out.println(person+"到達山頂");
        }

        public void step4Task() throws InterruptedException {
            String person = "伙伴【"+Thread.currentThread().getName()+"】";
            System.out.println(person+"開始休息");
            Thread.sleep(random.nextInt(5000));
            System.out.println(person+"休息結(jié)束,下山回家");
        }
    }
}

/**
 * 伙伴【Thread-3】從家出發(fā)了......
 * 伙伴【Thread-1】從家出發(fā)了......
 * 伙伴【Thread-2】從家出發(fā)了......
 * 伙伴【Thread-4】從家出發(fā)了......
 * 伙伴【Thread-0】從家出發(fā)了......
 * 伙伴【Thread-1】到達佘山站
 * 伙伴【Thread-4】到達佘山站
 * 伙伴【Thread-3】到達佘山站
 * 伙伴【Thread-0】到達佘山站
 * 伙伴【Thread-2】到達佘山站
 * 大家都到佘山站了,可以出發(fā)去佘山了,人數(shù):5
 * 伙伴【Thread-3】出發(fā)去佘山
 * 伙伴【Thread-2】出發(fā)去佘山
 * 伙伴【Thread-4】出發(fā)去佘山
 * 伙伴【Thread-1】出發(fā)去佘山
 * 伙伴【Thread-0】出發(fā)去佘山
 * 伙伴【Thread-1】到達佘山
 * 伙伴【Thread-4】到達佘山
 * 伙伴【Thread-3】到達佘山
 * 伙伴【Thread-0】到達佘山
 * 伙伴【Thread-2】到達佘山
 * 大家都到佘山了,出發(fā)去爬山,人數(shù):5
 * 伙伴【Thread-1】出發(fā)去爬山
 * 伙伴【Thread-4】出發(fā)去爬山
 * 伙伴【Thread-0】出發(fā)去爬山
 * 伙伴【Thread-2】出發(fā)去爬山
 * 伙伴【Thread-3】出發(fā)去爬山
 * 伙伴【Thread-6】中途加入
 * 伙伴【Thread-6】出發(fā)去爬山
 * 伙伴【Thread-5】中途加入
 * 伙伴【Thread-5】出發(fā)去爬山
 * 伙伴【Thread-2】到達山頂
 * 伙伴【Thread-5】到達山頂
 * 伙伴【Thread-0】到達山頂
 * 伙伴【Thread-4】到達山頂
 * 伙伴【Thread-4】中途山腰返回
 * 伙伴【Thread-6】到達山頂
 * 伙伴【Thread-3】到達山頂
 * 伙伴【Thread-3】中途山腰返回
 * 伙伴【Thread-1】到達山頂
 * 大家都到山頂了,開始休息,人數(shù):5
 * 伙伴【Thread-5】開始休息
 * 伙伴【Thread-2】開始休息
 * 伙伴【Thread-6】開始休息
 * 伙伴【Thread-0】開始休息
 * 伙伴【Thread-1】開始休息
 * 伙伴【Thread-2】休息結(jié)束,下山回家
 * 伙伴【Thread-0】休息結(jié)束,下山回家
 * 伙伴【Thread-1】休息結(jié)束,下山回家
 * 伙伴【Thread-5】休息結(jié)束,下山回家
 * 伙伴【Thread-6】休息結(jié)束,下山回家
 */

應(yīng)用場景總結(jié)

以下是一些常見的 Phaser 應(yīng)用場景:

  1. 多線程任務(wù)分配:Phaser 可以用于將復(fù)雜的任務(wù)分配給多個線程執(zhí)行,并協(xié)調(diào)線程間的合作。
  2. 多級任務(wù)流程:Phaser 可以用于實現(xiàn)多級任務(wù)流程,在每一級任務(wù)完成后觸發(fā)下一級任務(wù)的開始。
  3. 模擬并行計算:Phaser 可以用于模擬并行計算,協(xié)調(diào)多個線程間的工作。
  4. 階段性任務(wù):Phaser 可以用于實現(xiàn)階段性任務(wù),在每一階段任務(wù)完成后觸發(fā)下一階段任務(wù)的開始。

到此這篇關(guān)于Java并發(fā)工具類Phaser詳解的文章就介紹到這了,更多相關(guān)Java的Phaser內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • IDEA Maven源修改為國內(nèi)阿里云鏡像的正確方式

    IDEA Maven源修改為國內(nèi)阿里云鏡像的正確方式

    為了加快 Maven 依賴的下載速度,可以將 Maven 的中央倉庫源修改為國內(nèi)的鏡像,比如阿里云鏡像,以下是如何在 IntelliJ IDEA 中將 Maven 源修改為阿里云鏡像的詳細步驟,感興趣的同學(xué)可以參考閱讀一下
    2024-09-09
  • netty?pipeline中的inbound和outbound事件傳播分析

    netty?pipeline中的inbound和outbound事件傳播分析

    這篇文章主要為大家介紹了netty?pipeline中的inbound和outbound事件傳播分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-04-04
  • Mybatis mapper接口動態(tài)代理開發(fā)步驟解析

    Mybatis mapper接口動態(tài)代理開發(fā)步驟解析

    這篇文章主要介紹了Mybatis mapper接口動態(tài)代理開發(fā)步驟解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-07-07
  • Java更新調(diào)度器(update scheduler)的使用詳解

    Java更新調(diào)度器(update scheduler)的使用詳解

    Java更新調(diào)度器是Java中的一個特性,可以自動化Java應(yīng)用程序的更新過程,它提供了一種方便的方式來安排Java應(yīng)用程序的更新,確保其與最新的功能、錯誤修復(fù)和安全補丁保持同步,本文將深入介紹如何使用Java更新調(diào)度器,并解釋它對Java開發(fā)人員和用戶的好處
    2023-11-11
  • springboot使用DynamicDataSource動態(tài)切換數(shù)據(jù)源的實現(xiàn)過程

    springboot使用DynamicDataSource動態(tài)切換數(shù)據(jù)源的實現(xiàn)過程

    這篇文章主要給大家介紹了關(guān)于springboot使用DynamicDataSource動態(tài)切換數(shù)據(jù)源的實現(xiàn)過程,Spring Boot應(yīng)用中可以配置多個數(shù)據(jù)源,并根據(jù)注解靈活指定當(dāng)前使用的數(shù)據(jù)源,需要的朋友可以參考下
    2023-08-08
  • JDBC的擴展知識點總結(jié)

    JDBC的擴展知識點總結(jié)

    這篇文章主要介紹了JDBC的擴展知識點總結(jié),文中有非常詳細的代碼示例,對正在學(xué)習(xí)JDBC的小伙伴們有很好地幫助,需要的朋友可以參考下
    2021-05-05
  • SpringBoot之Json的序列化和反序列化問題

    SpringBoot之Json的序列化和反序列化問題

    這篇文章主要介紹了SpringBoot之Json的序列化和反序列化問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • Java錯誤org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.sjks.mapper.Use

    Java錯誤org.apache.ibatis.binding.BindingException: Inval

    本文主要介紹了Java錯誤org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.sjks.mapper.Use,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • java 判斷二進制文件的方法

    java 判斷二進制文件的方法

    這篇文章主要介紹了java 判斷二進制文件的方法的相關(guān)資料,這里提供實例來實現(xiàn)判斷文件是否問二進制文件,希望能幫助到大家,需要的朋友可以參考下
    2017-09-09
  • Sa-Token 基礎(chǔ)及 Spring Boot 集成實戰(zhàn)指南

    Sa-Token 基礎(chǔ)及 Spring Boot 集成實戰(zhàn)指南

    Sa-Token是輕量級Java權(quán)限認(rèn)證框架,支持登錄、權(quán)限、單點登錄等場景,集成SpringBoot簡便,提供豐富注解和模塊化設(shè)計,相比Shiro和SpringSecurity更易用且適合中小型項目,注重安全與擴展性,本文給大家介紹Sa-Token基礎(chǔ)及Spring Boot集成實戰(zhàn)指南,感興趣的一起看看吧
    2025-07-07

最新評論

罗田县| 龙里县| 罗定市| 玉龙| 金山区| 漾濞| 澜沧| 玉田县| 越西县| 延寿县| 钦州市| 德州市| 乃东县| 安国市| 广丰县| 屯留县| 资阳市| 益阳市| 石首市| 神池县| 额济纳旗| 富民县| 丽水市| 颍上县| 卢湾区| 额尔古纳市| 共和县| 蒙城县| 土默特左旗| 延川县| 乌鲁木齐市| 潜江市| 沈阳市| 南开区| 油尖旺区| 湘西| 墨江| 鄂温| 万安县| 临夏县| 安陆市|