Phaser类实现并发多阶段同步

package com.copycat.concurrent;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
/**
 *  Phaser是并发多阶段任务的管理类,线程完成一个阶段后等待其它线程到达同样的阶段,再执行下一个阶段的任务
 *  参考博客:http://www.cnblogs.com/wxgblogs/p/5431671.html
 *  详细的描述查看java的开发文档手册
 *  1.在指定文件夹及其子文件夹中获得扩展名为.log的文件
 *  2.对第一步的结果过滤,删除修改时间超过24小时的文件
 *  3.将结果打印数据到控制台
 */
public class FileSearch implements Runnable {
    private String initPath;// 查找路径
    private String end;// 文件后缀
    private List<String> results;// 结果集
    private Phaser phaser;
    
    public FileSearch(String initPath, String end, Phaser phaser)
    {
        this.initPath = initPath;
        this.end = end;
        this.phaser = phaser;
        this.results = new ArrayList<String>();
    }
    private void direactoryProcess(File file)
    {
        File list[] = file.listFiles();
        if (list != null) {
            for (File file2 : list) {
                if (file2.isDirectory()) {
                    direactoryProcess(file2);
                }
                else 
                {
                    if(file2.getName().endsWith(end))
                    {
                        results.add(file2.getAbsolutePath());
                    }
                }
            }
        }
    }
   /**
    * 过滤掉修改时间大于一天的文件
    */
    private void filterResult() {
        List<String> newResult = new ArrayList<String>();
        long actualDate = new Date().getTime();
        for (int i = 0; i < results.size(); i++) 
        {
            File file = new File(results.get(i));
            long lastModifyTime = file.lastModified();
            if (actualDate - lastModifyTime < TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS))
            {
                newResult.add(results.get(i));
            }
        }
        results = newResult;
    }
    private boolean checkResults()
    {
        if (results.isEmpty())
        {
            System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is 0");
            phaser.arriveAndDeregister();/*完成的线程要取消注册,这样相当于把这个线程从Phaser中去掉*/
            System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is 0");
            return false;
        } else {
            System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
            phaser.arriveAndAwaitAdvance();/*未完成的线程在完成当前的阶段后要等待其它线程也达到同一阶段*/
            System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
            return true;
        }
    }
    private void showInfo() {
        for (int i = 0; i < results.size(); i++) 
        {
            System.out.println(Thread.currentThread().getName() + ":"+ results.get(i));
        }
        System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
        phaser.arriveAndAwaitAdvance();
        System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
        File file=new File(initPath);
        if(file.isDirectory()){
            direactoryProcess(file);
        }
        if(!checkResults()){
            return;
        }
        filterResult();
        if(!checkResults()){
            return;
        }
        showInfo();
        System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
        phaser.arriveAndDeregister();
        System.out.println(Thread.currentThread().getName() + ": Phase "+ phaser.getPhase() + " the size of result is " + results.size());
    }
    public static void main(String[] args)
    {
        Phaser phaser=new Phaser(3);/*三个线程要公用一个Phaser*/
        FileSearch fileSearch1=new FileSearch("c:\\Windows", "log", phaser);
        FileSearch fileSearch2=new FileSearch("C:\\Programs Files", "log", phaser);
        FileSearch fileSearch3=new FileSearch("C:\\Tencent", "log", phaser);
        Thread thread1=new Thread(fileSearch1, "fileSearch1");
        thread1.start();
        Thread thread2=new Thread(fileSearch2, "fileSearch2");
        thread2.start();
        Thread thread3=new Thread(fileSearch3, "fileSearch3");
        thread3.start();
        try 
        {
            thread1.join();
            thread2.join();
            thread3.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Terminated:"+ phaser.isTerminated());
    }
}

猜你喜欢

转载自blog.csdn.net/qq_28816195/article/details/78311066
今日推荐