Java基础-线程并发工具类

Android知识终结

一、分而治之原理(fork/join )

在计算机十大经典算法中,快速排序归并排序二分查找用的是分而治之原理。

1、定义

在Java的Fork/Join框架中,使用两个类完成上述操作

  • 1、ForkJoinTask:我们要使用Fork/Join框架,首先需要创建一个ForkJoin任务。该类提供了在任务中执行fork和join的机制。通常情况下我们不需要直接集成ForkJoinTask类,只需要继承它的子类,Fork/Join框架提供了两个子类:
  • RecursiveTask同步用法同时演示有返回结果,统计整形数组中所有元素的和。
  • RecursiveAction异步用法同时演示不要求返回值,遍历指定目标(含子目录)寻找指定类型文件。
  • 2、ForkJoinPool:ForkJoinTask需要通过ForkJoinPool来执行。
  • 任务分割出的子任务会添加到当前工作线程所维护的双端队列中,进入队列的头部。当一个工作线程的队列里暂时没有任务时,它会随机从其他工作线程的队列的尾部获取一个任务(工作窃取算法)。

2、归并排序-同步用法

2.1、数组集合

public class MakeArray {
    public static final int MAX_COUNT = 40000;

    public static int[] getArrays(){
        int[] nums = new int[MAX_COUNT];
        Random random = new Random();
        for (int i = 0; i < MAX_COUNT; i++) {
            nums[i] = random.nextInt(MAX_COUNT);
        }
        return nums;
    }
}

2.2、求数组中的和

public class SunArray {
    public static class SumTask extends RecursiveTask<Integer>{
        private static final int THRESHOLD = MakeArray.MAX_COUNT/10;
        private int[] nums;
        private int fromIndex;
        private int toIndex;

        public SumTask(int[] nums, int fromIndex, int toIndex) {
            this.nums = nums;
            this.fromIndex = fromIndex;
            this.toIndex = toIndex;
        }

        @Override
        protected Integer compute() { //运用递归算法
            if (toIndex - fromIndex < THRESHOLD){
                System.out.println("form index = " + fromIndex + "toIndex = " + toIndex);
                int count = 0;
                for (int i = fromIndex; i < toIndex; i++) {
                    count += nums[i];
                }
                return count;
            } else {
                int mid = (toIndex + fromIndex) / 2;
                SumTask left = new SumTask(nums, fromIndex, mid);
                SumTask right = new SumTask(nums, mid, toIndex);
                invokeAll(left, right);
                return left.join() + right.join();
            }
        }
    }
    
    public static void main(String[] argc){
        int[] arrays = MakeArray.getArrays();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SumTask sumTask = new SumTask(arrays, 0, arrays.length);
        long start = System.currentTimeMillis();
        forkJoinPool.invoke(sumTask);
        System.out.println("The count is" + sumTask.join() +
                "spend time" + (System.currentTimeMillis() - start) + "ms");
    }
}

3、异步用法

/**
 *类说明:遍历指定目录(含子目录)找寻指定类型文件
 */
public class FindDirsFiles extends RecursiveAction {
    private File path;
    public FindDirsFiles(File path) {
        this.path = path;
    }
    @Override
    protected void compute() {
        List<FindDirsFiles> subTasks = new ArrayList<>();
        File[] files = path.listFiles();
        if (files!=null){
            for (File file : files) {
                if (file.isDirectory()) {
                    // 对每个子目录都新建一个子任务。
                    subTasks.add(new FindDirsFiles(file));
                } else {
                    // 遇到文件,检查。
                    if (file.getAbsolutePath().endsWith("txt")){
                        System.out.println("文件:" + file.getAbsolutePath());
                    }
                }
            }
            if (!subTasks.isEmpty()) {
                // 在当前的 ForkJoinPool 上调度所有的子任务。
                for (FindDirsFiles subTask : invokeAll(subTasks)) {
                    subTask.join();
                }
            }
        }
    }

    public static void main(String [] args){
        try {
            // 用一个 ForkJoinPool 实例调度总任务
            ForkJoinPool pool = new ForkJoinPool();
            FindDirsFiles task = new FindDirsFiles(new File("F:/"));

            /*异步提交*/
            pool.execute(task);
            /*主线程做自己的业务工作*/
            System.out.println("Task is Running......");
            Thread.sleep(1);
            int otherWork = 0;
            for(int i=0;i<100;i++){
                otherWork = otherWork+i;
            }
            System.out.println("Main Thread done sth......,otherWork=" +otherWork);
            task.join();//阻塞方法
            System.out.println("Task end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

二、CountDownLatch 计数器

  • countDownLatch这个类使一个线程等待其他线程各自执行完毕后再执行。
  • 是通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,闭锁上等待的线程就可以恢复工作了。
  • 使用AQS的共享方式,内部实现了AbstractQueuedSynchronizer的内部类。
    private static final class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 4982264981922014374L;
        Sync(int count) {
            setState(count);
        }
        int getCount() {
            return getState();
        }
        protected int tryAcquireShared(int acquires) {
            return (getState() == 0) ? 1 : -1;
        }
        protected boolean tryReleaseShared(int releases) {
            // Decrement count; signal when transition to zero
            for (;;) {
                int c = getState();
                if (c == 0)
                    return false;
                int nextc = c - 1;
                if (compareAndSetState(c, nextc))
                    return nextc == 0;
            }
        }
    }

注意:一个线程可以多次减一;闭锁线程可以有多个且闭锁线程执行任务时其他线程可能还在执行

示例演示

/**
 *类说明:演示CountDownLatch用法,
 * 共5个初始化子线程,6个闭锁扣除点,扣除完毕后,主线程和业务线程才能继续执行
 */
public class UseCountDownLatch {
    static CountDownLatch latch = new CountDownLatch(6);
    /*初始化线程*/
    private static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("Thread_" + Thread.currentThread().getId()
                    + " ready init work......");
            latch.countDown();
            for (int i = 0; i < 2; i++) {
                System.out.println("Thread_" + Thread.currentThread().getId()
                        + " ........continue do its work");
            }
        }
    }

    /*业务线程等待latch的计数器为0完成*/
    private static class MyThread implements Runnable {
        @Override
        public void run() {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println("BusiThread_" + Thread.currentThread().getId()
                        + " do business-----");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1);
                    System.out.println("Thread_" + Thread.currentThread().getId()
                            + " ready init work step 1st......");
                    latch.countDown();
                    System.out.println("begin step 2nd.......");
                    Thread.sleep(1);
                    System.out.println("Thread_" + Thread.currentThread().getId()
                            + " ready init work step 2nd......");
                    latch.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(new MyThread()).start();
        for (int i = 0; i <= 3; i++) {
            Thread thread = new Thread(new MyRunnable());
            thread.start();
        }
        latch.await();
        System.out.println("Main do ites work........");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章