1. 程式人生 > >Java實現多線程的四種實現方式

Java實現多線程的四種實現方式

lis star 維護 invoke 1.0 threads arraylist urn fix

以計算0到1000之間的和為例

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
//求1~N全部整數的和,會上溢
int N = (int) 1e8;
int threadSize = 5;

/**
 * 最原始最基礎的方式:使用thread,自定義並發
 */
class ThreadJoin {
    void go() {
        Thread[] a = new Thread[threadSize];
        //每個線程應該幹多少活
        int per = (int) Math.ceil(N * 1.0 / a.length);
        final AtomicInteger s = new AtomicInteger(0);
        for (int i = 0; i < a.length; i++) {
            int ii = i;
            a[i] = new Thread(() -> {
                int sum = 0;
                for (int j = ii * per; j < Math.min(ii * per + per, N); j++) {
                    sum += j;
                }
                s.addAndGet(sum);
            });
            a[i].start();
        }
        for (Thread i : a)
            try {
                i.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        System.out.println(s.get() + " " + getClass().getName());
    }
}

/**
 * 重量級的多線程框架:ThreadPoolExecutor,維護一個動態線程池
 */
class UseThreadPoolExecutor {
    void go() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(threadSize, threadSize, 1, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        int per = (int) (Math.ceil(1.0 * N / threadSize));
        List<Future<Integer>> futureList = new LinkedList<>();
        for (int i = 0; i < threadSize; i++) {
            final int ii = i;
            futureList.add(executor.submit(() -> {
                int sum = 0;
                for (int j = ii * per; j < Math.min(N, ii * per + per); j++) {
                    sum += j;
                }
                return sum;
            }));
        }
        int sum = 0;
        for (Future<Integer> j : futureList) {
            try {
                sum += j.get(Integer.MAX_VALUE, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        executor.shutdown();
        System.out.println(sum + " " + getClass().getName());
    }
}

/**
 * ExecutorService:輕量級的線程池
 */
class UseExecutorService {
    void go() {
        ExecutorService service = Executors.newFixedThreadPool(threadSize);
        int per = (int) (Math.ceil(N * 1.0 / threadSize));
        List<Future<Integer>> futureList = new LinkedList<>();
        for (int i = 0; i < threadSize; i++) {
            final int ii = i;
            futureList.add(service.submit(() -> {
                int sum = 0;
                for (int j = ii * per; j < Math.min(N, ii * per + per); j++) {
                    sum += j;
                }
                return sum;
            }));
        }
        int sum = 0;
        for (Future<Integer> j : futureList) {
            try {
                sum += j.get(Integer.MAX_VALUE, TimeUnit.SECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        service.shutdown();
        System.out.println(sum + " " + getClass().getName());
    }
}

/**
 * 模擬Linux fork join操作
 */

class UseForkJoin {
    void go() {
        int per = (int) (Math.ceil(1.0 * N / threadSize));
        List<ForkJoinTask<Integer>> a = new ArrayList<>(threadSize);
        for (int i = 0; i < threadSize; i++) {
            final int ii = i;
            a.add(new RecursiveTask<Integer>() {
                @Override
                protected Integer compute() {
                    int sum = 0;
                    for (int j = ii * per; j < Math.min(N, ii * per + per); j++) {
                        sum += j;
                    }
                    return sum;
                }
            });
            a.get(i).invoke();
        }
        int s = 0;
        for (ForkJoinTask<Integer> i : a) {
            s += i.join();
        }
        System.out.println(s + " " + getClass().getName());
    }
}

Main() {
    new ThreadJoin().go();
    new UseExecutorService().go();
    new UseThreadPoolExecutor().go();
    new UseForkJoin().go();
}

public static void main(String[] args) {
    new Main();
}
}

Java實現多線程的四種實現方式