第五章 Fork/Join Framework(Fork/join 框架)【上】

本章涉及的内容:

  • 创建一个Fork/Join 池
  • 插入任务的结果
  • 同步运行任务
  • 在任务中抛出异常
  • 取消一个任务

1、简介

问题来了,Fork/Join为啥需要存在? 前面Executor已经解决线程管理的问题,为甚还有Fork/Join框架?打个比方,公司管理,刚开始只要六七人,一个管理员就够了,随着人员的增加多管理难度越来越大,那应该怎么办呢?按部门分开管理,比如财务部,后勤部,策划部,研发部等等,每个部门选一个小领导,然后只要管理小领导就可以。Fork/Join也是这样思想,分而治之,将任务适当分解,来提供效率。


具体怎么分取决于你具体的任务的情况。

框架基于如下两种操作:

fork 操作:拆分任务和执行任务

join操作: 等待任务完成(插队操作)

Fork/Join 和 Executor最大区别就是,Fork/Join采用的是work-stealing(任务窃取)算法, 简单来说它线程称为工作线程,它在做完一个任务之后,它会继续找其他任务做,(也就是积极主动找活干,不像Executor那样死等别人做完而不帮忙)。

当然让它找活干得有条件:

  • 1、任务只能使用fork() 和join()操作来实现同步机制。如果使用其他同步机制,在同步操作的时候,这个工作线程将不会执行其它任务,例如 如果在Fork/join框架中执行sleep(休眠的方法),那么这个工作线程在休眠期间将不会执行其他任务。
  • 2、任务不应该执行I/O操作,例如读写文件
  • 3、任务不能抛出一个检查异常。必须包含代码去捕获和处理异常。(出现异常,线程大哥也是崩溃的)

Fork/Join框架核心的两个类:

  • ForkJoinPool: 它实现了ExecutorService接口和work-stealing算法。它管理工作线程和提供任务的状态和他们执行情况
  • ForkJoinTask: 它是一个基础的任务类,它将在ForkJoinPool中执行。它提供执行fork()和join()操作的机制。通常情况下。为了实现Fork/Join任务。你将会实现两个子类。一个是没有返回值的RecursiveAction和一个有返回值RecursiveTask。

2、创建一个Fork/Join池

例子:

为产品调价

package com.jack;

public class Product {
	private String name;
	private double price;
	public String getName() {
		return name;
	}
	public double getPrice() {
		return price;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	
	
}

package com.jack;

import java.util.ArrayList;
import java.util.List;

public class ProductListGenerator {
	public List<Product> generate (int size){
		List<Product> ret = new ArrayList<Product>();
		for (int i=0; i<size; i++){
			Product product = new Product();
			product.setName("Product " + i);
			product.setPrice(10);
			ret.add(product);
		}
		return ret;
	}
}

总结:模拟产品

package com.jack;

import java.util.List;
import java.util.concurrent.RecursiveAction;

public class Task extends RecursiveAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8478224658216264382L;

	private List<Product> products;
	private int first;
	private int last;
	private double increment;  //增量
	
	
	public Task(List<Product> products, int first, int last, double increment) {
		super();
		this.products = products;
		this.first = first;
		this.last = last;
		this.increment = increment;
	}


	@Override
	protected void compute() {
		if (last -first <10){
			updatePrices();
		}else {
			int middle = (last+first)/2;
			System.out.printf("任务:挂起的任务: %s\n", getQueuedTaskCount());
			Task t1 = new Task(products, first, middle+1, increment);
			Task t2 = new Task(products, middle+1, last, increment);
			invokeAll(t1,t2);
		}
		
	}


	private void updatePrices() {
		for (int i=first; i<last; i++){
			Product product = products.get(i);
			product.setPrice(product.getPrice()*(1+increment));
		}
	}

}

总结:

1、继承RecursiveAction,同时重写compute方法,这个方法就是确定任务拆分规则,这里是大于10个就拆分,不断递归拆分

2、invokeAll(t1,t2) 将子任务重新调用compute方法。

 

package com.jack;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Main {
	public static void main(String[] args) {
		ProductListGenerator generator = new ProductListGenerator();
		List<Product> products = generator.generate(10000);
		Task task = new Task(products, 0, products.size(), 0.20);
		ForkJoinPool pool = new ForkJoinPool();
		pool.execute(task);
		do {
			System.out.printf("Main: 线程数量:%d\n", pool.getActiveThreadCount());
			System.out.printf("Main: 线程窃取:%d\n",pool.getStealCount());
			System.out.printf("Main: 平行任务:%d\n", pool.getParallelism());
			try {
				TimeUnit.MILLISECONDS.sleep(5);
			} catch (InterruptedException e){
				e.printStackTrace();
			}
		}while (!task.isDone());
		pool.shutdown();
		if(task.isCompletedNormally()){
			System.out.printf("Main: 这个工程正常结束了\n");
		}
		for (int i=0; i<products.size(); i++){
			Product product = products.get(i);
			if(product.getPrice() != 12){
				System.out.printf("产品 %s: %f\n", product.getName(), product.getPrice());
			}
		}
		System.out.println("Main: 执行完毕\n");
	}
}

日志:


总结:(执行过程)

  • 1、模拟生产产品
  • 2、创建ForkJoinPool可以执行的任务也就是继承了RecursiveAction类
  • 3、创建执行者 ForkJoinPool
  • 4、循环判断线程执行状态:包含线程数量、线程窃取、平行任务等等。直到所有任务完成(isDone)
  • 5、关闭池pool.shutdown()
  • 6、判断任务是否都是正常退出 isCompletedNormally()
  • 7、判断产品是否增加正确

扩展:

  • 1、execute(Runnable task): ForkJoinPool可以执行Runnable接口的任务,但是不能应用work-stealing算法。这个算法只适合ForkJoinTask对象
  • 2、invoke(ForkJoinTask<T> task) : 默认上面例子execute()方法就是异步调用ForkJoinPool类,若要同步调用使用invoke()方法。这个方法不会返回,直到当参数传入的任务执行完毕。
  • 3、你可以使用ExecutorService 的invokeAll()方法和invokeAny()方法, 这些方法接受的Callable对象作为参数。但是如果使用ForkJoinPool执行不会使用work-stealing算法,所以最好还是Executor进行执行上述方法。
  • 4、invokeAll(ForkJoinTask<?>... tasks) :任务数不确定
  • 5、inovkeAll(Collection<T> tasks): 这个接受一个任务集合,T必须是ForkJoinTask类或子类。

3、执行任务返回结果

如果执行任务返回结果需要继承RecursiveTask, 它继承了ForkJoinTask 和实现了Executor框架Future接口。

例子:模拟文档查找某个词语

  • 1、文档任务,它将会去多行中寻找一个词语
  • 2、行任务,它将在文档某个部分去寻找词语

package com.jack;

import java.util.Random;

public class Document {
	private String words[] = {"the", "hello","goodbye","packt", "join", "thread","pool","random","class","main"};
	
	public String [][] generateDocument (int numLines, int numWords, String word) {
		int counter =0;
		String document[][] = new String[numLines][numWords];
		Random random = new Random();
		for (int i=0; i<numLines; i++){
			for(int j=0; j<numWords; j++){
				int index = random.nextInt(words.length);
				document[i][j] = words[index];
				if(document[i][j].equals(word)) {
					counter++;
				}
			}
		}
		System.out.printf("文档模拟: 这个词语在文档中出现 %d次数\n ", counter);
		return document;
	}

}
总结:模拟生产一个文档,统计一下某个词出现次数,那个次数与线程执行结果进行对比

package com.jack;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

public class DocumentTask extends RecursiveTask<Integer>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 6079965024017517277L;
	private String document[][];
	private int start, end;
	private String word;
	
	public DocumentTask(String[][] document, int start, int end, String word) {
		super();
		this.document = document;
		this.start = start;
		this.end = end;
		this.word = word;
	}

	@Override
	protected Integer compute() {
		int result =0;
		if(end - start <10){
			result = processLines(document, start, end, word);
		} else {
			int mid = (start+end)/2;
			DocumentTask task1 =new DocumentTask(document, start, mid, word);
			DocumentTask task2 = new DocumentTask(document, mid, end, word);
			invokeAll(task1, task2);
			try {
				result = groupResults(task1.get(), task2.get());
			} catch (InterruptedException | ExecutionException e){
				e.printStackTrace();
			}
					
		}
		return result;
	}

	private int groupResults(Integer num1, Integer num2) {
		
		return num1+num2;
	}

	private int processLines(String[][] document, int start, int end, String word) {
		List<LineTask> tasks = new ArrayList<LineTask>();
		for (int i = start; i<end; i++){
			LineTask task = new LineTask(document[i], 0, document[i].length, word);
			tasks.add(task);
		}
		invokeAll(tasks);
		int result =0;
		for (int i=0; i<tasks.size(); i++){
			LineTask task = tasks.get(i);
			try {
				result = result + task.get();
				
			} catch (InterruptedException | ExecutionException e){
				e.printStackTrace();
			}
		}
		return new Integer(result);
	}

}

总结:

1、将文档以小于十行单位进行分隔任务,同时将任务结果进行统计

2、在为每一行创建一个行任务,获取行任务的结果累加

package com.jack;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

public class LineTask extends RecursiveTask<Integer>{

	/**
	 * 
	 */
	private static final long serialVersionUID = -6010479705104034522L;

	private String line[];
	private int start, end;
	private String word;
	
	public LineTask(String[] line, int start, int end, String word) {
		super();
		this.line = line;
		this.start = start;
		this.end = end;
		this.word = word;
	}

	@Override
	protected Integer compute() {
		Integer result = null;
		if(end - start<100){
			result = count(line, start, end, word);
		} else {
			int mid = (start + end)/2;
			LineTask task1 = new LineTask(line, start, mid, word);
			LineTask task2 = new LineTask(line, mid, end, word);
			invokeAll(task1, task2);
			try {
				result = groupResults(task1.get(), task2.get());
			} catch (InterruptedException | ExecutionException e){
				e.printStackTrace();
			}
		}
		return result;
	}

	private Integer groupResults(Integer num1, Integer num2) {
		
		return num1+num2;
	}

	private Integer count(String[] line, int start, int end, String word) {
		int counter;
		counter=0;
		for (int i=start; i<end; i++){
			if(line[i].equals(word)){
				counter++;
			}
		}
		try {
			Thread.sleep(10);
		} catch (InterruptedException e){
			e.printStackTrace();
		}
		return counter;
	}
	

}
总结:

跟Document类似。行任务,如果字数大于100,继续拆分行任务。

package com.jack;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Main {
	public static void main(String[] args) {
		Document mock = new Document();
		String[][] document = mock.generateDocument(100, 1000, "the");
		DocumentTask  task = new DocumentTask(document, 0, 100, "the");
		ForkJoinPool pool = new ForkJoinPool();
		pool.execute(task);
		do {
			System.out.printf("******************************\n");
			System.out.printf("Main: 并行线程: %d\n", pool.getParallelism());
			System.out.printf("Main:活动线程: %d\n", pool.getActiveThreadCount());
			System.out.printf("Main: 任务数量: %d\n", pool.getQueuedTaskCount());
			System.out.printf("Main: 窃取线程: %d\n", pool.getStealCount());
			System.out.printf("************************************\n");
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e){
				e.printStackTrace();
			}
		}while (!task.isDone());
		pool.shutdown();
		try {
			pool.awaitTermination(1, TimeUnit.DAYS);
			
		} catch (InterruptedException e){
			e.printStackTrace();
		}
		try {
			System.out.printf("Main : 词语出现文档的次数%d", task.get());
		} catch (InterruptedException | ExecutionException e){
			e.printStackTrace();
		}
	}
}
总结:(执行过程)

  • 1、创建一个文档对象模拟生成一个文档
  • 2、创建一个文档任务,同时指定查找的内容"the"
  • 3、创建ForkJoinPool 对象
  • 4、执行任务 execute
  • 5、直到所有任务执行完(isDone)
  • 6、关闭pool.shutdown() 。
  • 7、pool.awaitTermination()防止main提前结束
  • 8、获取最后的结果

日志:

文档模拟: 这个词语在文档中出现 9898次数
 ******************************
Main: 并行线程: 4
Main:活动线程: 2
Main: 任务数量: 2
Main: 窃取线程: 0
************************************
******************************
Main: 并行线程: 4
Main:活动线程: 4
Main: 任务数量: 34
Main: 窃取线程: 0
************************************
******************************
Main: 并行线程: 4
Main:活动线程: 4
Main: 任务数量: 32
Main: 窃取线程: 0
************************************
******************************
Main: 并行线程: 4
Main:活动线程: 4
Main: 任务数量: 32
Main: 窃取线程: 0
************************************
Main : 词语出现文档的次数9898

4、异步运行任务

你可以在ForkJoinPoll中执行ForkJoinTask任务可以使同步和异步。

同步:方法发送任务之后不会立即返回结果,直到任务完成(监工)

异步:方法发送任务之后会立即返回结果,任务在后台运行(分配任务)

对于同步方法(invokeAll())允许执行work-stealing算法。

对于异步方法(fork()),不允许执行work-stealing算法, 只能使用join()或get()等待最后的结果。

例子:

学习使用异步方法来去查找文件夹特定后缀的文件列表。

package com.jack;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class FolderProcessor extends RecursiveTask<List<String>> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4052818353771792401L;

	private String path;
	private String extension;
	
	
	public FolderProcessor(String path, String extension) {
		super();
		this.path = path;
		this.extension = extension;
	}


	@Override
	protected List<String> compute() {
		List<String> list = new ArrayList<>();
		List<FolderProcessor> tasks = new ArrayList<>();
		File file = new File (path);
		File content[] = file.listFiles();
		
		if(content !=null){
			for (int i=0; i<content.length; i++){
				if(content[i].isDirectory()) {
					FolderProcessor task = new FolderProcessor(content[i].getAbsolutePath(), extension);
					task.fork();
					tasks.add(task);
				}else {
					if(checkFile(content[i].getName())){
						list.add(content[i].getAbsolutePath());
					}
				}
			}
			if(tasks.size() >50){
				System.out.printf("%s: %d 任务运行。\n", file.getAbsolutePath(),tasks.size());
			}
			addResultsFromTasks(list, tasks);
		}
		return list;
	}


	private boolean checkFile(String name) {
		
		return name.endsWith(extension);
	}


	private void addResultsFromTasks(List<String> list, List<FolderProcessor> tasks) {
		for (FolderProcessor item: tasks){
			list.addAll(item.join());
		}
	}

}

总结:

  • 1、创建一个文件类FolderProcessor继承了RecursiveTask<T>接口
  • 2、关键方法就是compute()
  • 3、如果目录就是异步添加任务,就是fork()方法。
  • 4、将任务结果进行汇总处理,返回

package com.jack;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Main {
	public static void main(String[] args) {
		ForkJoinPool pool = new ForkJoinPool();
		FolderProcessor system = new FolderProcessor("C:\\Windows", "log");
		FolderProcessor apps = new FolderProcessor("C:\\Program Files", "log");
		pool.execute(system);
		pool.execute(apps);
		do {
			System.out.printf("**************************************\n");
			System.out.printf("Main : 并行的线程:%d\n", pool.getParallelism());
			System.out.printf("Main : 活动线程:%d\n", pool.getActiveThreadCount());
			System.out.printf("Main: 任务的数量:%d\n", pool.getQueuedTaskCount());
			System.out.printf("Main : 窃取线程: %d\n", pool.getStealCount());
			System.out.printf("***************************************\n");
			try{
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e){
				e.printStackTrace();
			}
		}while ((!system.isDone()) || (!apps.isDone()));
		pool.shutdown();
		List<String> results;
		results = system.join();
		System.out.printf("System : %d 文件被发现.\n", results.size());
		results = apps.join();
		System.out.printf("Apps: %d 文件找到\n", results.size());
	
	}
}


总结:

  • 1、创建一个ForkJoinPool执行者
  • 2、创建实现RecursiveTask<T>的实例
  • 3、执行任务 execute();
  • 4、直到完成就不打印信息,关闭执行者shutDown()
  • 5、RecursiveTask<T>的join()方法等待结果到了

日志:

**************************************
Main : 并行的线程:4
C:\Windows: 59 任务运行。
Main : 活动线程:4
Main: 任务的数量:297
Main : 窃取线程: 13
***************************************
C:\Windows\assembly\NativeImages_v2.0.50727_32: 119 任务运行。
C:\Windows\assembly\GAC_MSIL: 383 任务运行。
C:\Windows\assembly\NativeImages_v2.0.50727_64: 121 任务运行。
C:\Windows\assembly\NativeImages_v4.0.30319_32: 147 任务运行。
C:\Windows\assembly\NativeImages_v4.0.30319_64: 151 任务运行。
C:\Windows\Microsoft.NET\assembly\GAC_MSIL: 329 任务运行。
C:\Windows\System32\config\systemprofile\AppData\LocalLow\Sun\Java\Deployment\cache\6.0: 66 任务运行。
C:\Windows\System32\DriverStore\FileRepository: 307 任务运行。
C:\Windows\SysWOW64: 81 任务运行。
C:\Windows\System32: 93 任务运行。
**************************************
Main : 并行的线程:4
Main : 活动线程:21
Main: 任务的数量:3308
Main : 窃取线程: 2198
***************************************
**************************************
Main : 并行的线程:4
Main : 活动线程:5
Main: 任务的数量:1775
Main : 窃取线程: 13793
***************************************
C:\Windows\winsxs: 15320 任务运行。
**************************************
Main : 并行的线程:4
Main : 活动线程:1
Main: 任务的数量:0
Main : 窃取线程: 16960
***************************************
System : 94 文件被发现.
Apps: 2 文件找到

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值