上节部分并发编程(二)
-
Executor的使用
import java.util.concurrent.Executor; public class Demo1_Executor implements Executor { public static void main(String[] args) { Demo1_Executor demo1_executor = new Demo1_Executor(); demo1_executor.execute(()-> System.out.println("I am is Executor")); } @Override public void execute(Runnable command) { command.run(); } }
-
Callable的使用
import java.util.concurrent.*; /* * 认识Callable,对Runnable进行了扩展,由于重写了,不能抛出异常 * 对Callable的调用,可以有返回值,可以抛出异常 * Runnable没有返回值(最主要的区别) * */ public class Demo2_Callable implements Callable<Integer>{ @Override public Integer call() throws Exception { return 100; } public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<Integer> submit = executorService.submit(new Demo2_Callable()); System.out.println(submit.get()); executorService.shutdown(); } }
-
ThreadPool使用
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Demo3_ThreadPool { public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newFixedThreadPool(5); for (int i = 0; i < 6; i++) { service.execute(()->{ try { TimeUnit.MICROSECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); }); } System.out.println(service); service.shutdown(); System.out.println(service.isTerminated()); System.out.println(service.isShutdown()); System.out.println(service); TimeUnit.SECONDS.sleep(5); System.out.println(service.isTerminated()); System.out.println(service.isShutdown()); System.out.println(service); } }
-
Future的使用
import java.util.concurrent.*; public class Demo4_Future { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<Integer> task = new FutureTask<>(() -> { TimeUnit.MICROSECONDS.sleep(500); return 1000; }); new Thread(task).start(); System.out.println(task.get()); ExecutorService service = Executors.newFixedThreadPool(5); Future<Integer> f = service.submit(() -> { TimeUnit.MICROSECONDS.sleep(500); return 1; }); System.out.println(f.get()); System.out.println(f.isDone()); } }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; public class Demo5_ParalleComputing { public static void main(String[] args) throws ExecutionException, InterruptedException { long start = System.currentTimeMillis(); List<Integer> results = getPrime(1, 200000); long end = System.currentTimeMillis(); System.out.println(end - start); final int cupCoreNum = 8; ExecutorService executorService = Executors.newFixedThreadPool(cupCoreNum); MyTask myTask1 = new MyTask(1, 50000); MyTask myTask2 = new MyTask(50001, 100000); MyTask myTask3 = new MyTask(100001, 150000); MyTask myTask4 = new MyTask(150001, 200000); Future<List<Integer>> f1 = executorService.submit(myTask1); Future<List<Integer>> f2 = executorService.submit(myTask2); Future<List<Integer>> f3 = executorService.submit(myTask3); Future<List<Integer>> f4 = executorService.submit(myTask4); start = System.currentTimeMillis(); f1.get(); f2.get(); f3.get(); f4.get(); end = System.currentTimeMillis(); System.out.println(end - start); executorService.shutdown(); } static class MyTask implements Callable<List<Integer>> { int startPos, endPos; public MyTask(int startPos, int endPos) { this.startPos = startPos; this.endPos = endPos; } @Override public List<Integer> call() throws Exception { List<Integer> r = getPrime(startPos, endPos); return null; } } static boolean isPrime(int num) { for (int i = 2; i < Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } static List<Integer> getPrime(int start, int end) { List<Integer> results = new ArrayList<>(); for (int i = start; i <= end; i++) { if (isPrime(i) && i != 1) { results.add(i); } } return results; } }
-
CachePool的使用
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Demo6_CachePool { public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newCachedThreadPool(); System.out.println(service); for (int i = 0; i < 2; i++) { service.execute(()->{ try { TimeUnit.MICROSECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); }); } System.out.println(service); TimeUnit.SECONDS.sleep(60); System.out.println(service); TimeUnit.SECONDS.sleep(1); System.out.println(service); } }
-
SingleThreadPool的使用
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Demo7_SingleThreadPool { public static void main(String[] args) { ExecutorService service = Executors.newSingleThreadExecutor(); for (int i = 0; i < 5; i++) { final int j = i; service.execute(()->{ System.out.println(j + " " + Thread.currentThread().getName()); }); } } }
-
SchedulePool的使用
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Demo8_SchedulePool { public static void main(String[] args) { ScheduledExecutorService service = Executors.newScheduledThreadPool(4); service.scheduleAtFixedRate(() -> { try { TimeUnit.MICROSECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); }, 0, 500, TimeUnit.MILLISECONDS); } }
-
WorkStealingPool的使用
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class Demo9_WorkStealingPool { public static void main(String[] args) throws InterruptedException { ExecutorService service = Executors.newWorkStealingPool(); System.out.println(Runtime.getRuntime().availableProcessors()); service.execute(new R(1000)); service.execute(new R(2000)); service.execute(new R(2000)); service.execute(new R(2000)); service.execute(new R(2000)); service.execute(new R(2000)); service.execute(new R(2000)); service.execute(new R(2000)); service.execute(new R(2000)); TimeUnit.SECONDS.sleep(90); } static class R implements Runnable { int time; public R(int time) { this.time = time; } @Override public void run() { try { TimeUnit.MILLISECONDS.sleep(time); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(time + " " + Thread.currentThread().getName()); } } }
-
ForkJoinPool的使用
import java.util.Arrays; import java.util.Random; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import java.util.concurrent.TimeUnit; public class Demo10_ForkJoinPool { static int[] nums = new int[1000000]; static final int MAX_NUM = 50000; static Random r = new Random(); static { for (int i = 0; i < nums.length; i++) { nums[i] = r.nextInt(100); } System.out.println(Arrays.stream(nums).sum()); } /*static class AddTask extends RecursiveAction { int start, end; AddTask(int s, int e) { start = s; end = e; } @Override protected void compute() { if(end-start <= MAX_NUM) { long sum = 0L; for(int i=start; i<end; i++){ sum += nums[i]; } System.out.println(sum); } else { int middle = start + (end-start)/2; AddTask subTask1 = new AddTask(start, middle); AddTask subTask2 = new AddTask(middle, end); subTask1.fork(); subTask2.fork(); } } }*/ static class AddTask extends RecursiveTask<Long> { int start, end; AddTask(int s, int e) { start = s; end = e; } @Override protected Long compute() { if (end - start <= MAX_NUM) { long sum = 0L; for (int i = start; i < end; i++) { sum += nums[i]; } return sum; } int middle = start + (end - start) / 2; AddTask subTask1 = new AddTask(start, middle); AddTask subTask2 = new AddTask(middle, end); subTask1.fork(); subTask2.fork(); return subTask1.join() + subTask2.join(); } } public static void main(String[] args) { ForkJoinPool forkJoinPool = new ForkJoinPool(); AddTask task = new AddTask(0, nums.length); forkJoinPool.execute(task); long result = task.join(); System.out.println(result); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }