当前位置: 首页 > news >正文

Java对多线程~~~Fork/Join同步和异步帧

于Fork/Join骨架,当提交的任务,有两个同步和异步模式。它已被用于invokeAll()该方法是同步的。是任何

务提交后,这种方法不会返回直到全部的任务都处理完了。而还有还有一种方式,就是使用fork方法,这个是异步的。也

就是你提交任务后,fork方法马上返回。能够继续以下的任务。

这个线程也会继续执行。


以下我们以一个查询磁盘的以log结尾的文件的程序样例来说明异步的使用方法。


package com.bird.concursey.charpet8;

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

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

	private static final long serialVersionUID = 1L;
	
	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<String>();
		List<FolderProcessor> tasks = new ArrayList<FolderProcessor>();
		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 tasks ran.\n",file.getAbsolutePath(),tasks.size());
		}
		
		addResultsFromTasks(list,tasks);
		return list;
	}

	/**
	 * that will add to the list of files
the results returned by the subtasks launched by this task.
	 * @param list
	 * @param tasks
	 */
	private void addResultsFromTasks(List<String> list,
			List<FolderProcessor> tasks) {
		for(FolderProcessor item: tasks) {
			list.addAll(item.join());
		}
	}
	
	/**
	 * This method compares if the name of a file
passed as a parameter ends with the extension you are looking for
	 * @param name
	 * @return
	 */
	private boolean checkFile(String name) {
		return name.endsWith(extension);
	}
	
	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);
		
		pool.shutdown();
		
		List<String> results = null;
		results = system.join();
		System.out.printf("System: %d files found.\n",results.size());
		
		results = apps.join();
		System.out.printf("Apps: %d files found.\n",results.size());
		
		
	}
}

The key of this example is in the FolderProcessor class. Each task processes the content
of a folder. As you know, this content has the following two kinds of elements:


ff Files


ff Other folders


If the task finds a folder, it creates another Task object to process that folder and sends it to
the pool using the fork() method. This method sends the task to the pool that will execute it
if it has a free worker-thread or it can create a new one. The method returns immediately, so
the task can continue processing the content of the folder. For every file, a task compares its
extension with the one it's looking for and, if they are equal, adds the name of the file to the
list of results.


Once the task has processed all the content of the assigned folder, it waits for the finalization
of all the tasks it sent to the pool using the join() method. This method called in a task
waits for the finalization of its execution and returns the value returned by the compute()
method. The task groups the results of all the tasks it sent with its own results and returns
that list as a return value of the compute() method.


The ForkJoinPool class also allows the execution of tasks in an asynchronous way. You
have used the execute() method to send the three initial tasks to the pool. In the Main
class, you also finished the pool using the shutdown() method and wrote information about
the status and the evolution of the tasks that are running in it. The ForkJoinPool class
includes more methods that can be useful for this purpose. See the Monitoring a Fork/Join
pool recipe to see a complete list of those methods.


版权声明:本文博主原创文章,博客,未经同意不得转载。

相关文章:

  • Percona MySQL编译安装到CentOS6.5
  • MySQL 优化(memcache)
  • VS 远程发布IIS
  • KVM - virsh常用操作
  • SQL Server对比两字段的相似度(函数算法)
  • 成功部署SSIS中含有Oracle数据库连接的ETL包
  • ios申请真机调试( xcode 5)详细解析
  • 国家气象局免费天气预报接口,城市代码(JSON格式)
  • 第四次作业 合同管理、配置管理和外包管理
  • Git 1.9.5.msysgit.1
  • ​Java并发新构件之Exchanger
  • 本地管理员密码解决方案 Local Admin Password Solution (LAPS)
  • 自适应电脑、手机和iPad的网页设计方法
  • 团队博客作业Week4 --- 学霸网站--NABC
  • Effective Java
  • 【Linux系统编程】快速查找errno错误码信息
  • 2018天猫双11|这就是阿里云!不止有新技术,更有温暖的社会力量
  • CSS 三角实现
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • JavaScript 是如何工作的:WebRTC 和对等网络的机制!
  • JavaScript类型识别
  • java小心机(3)| 浅析finalize()
  • Objective-C 中关联引用的概念
  • Terraform入门 - 3. 变更基础设施
  • vue和cordova项目整合打包,并实现vue调用android的相机的demo
  • Webpack入门之遇到的那些坑,系列示例Demo
  • 第三十一到第三十三天:我是精明的小卖家(一)
  • 动态规划入门(以爬楼梯为例)
  • 更好理解的面向对象的Javascript 1 —— 动态类型和多态
  • 理解 C# 泛型接口中的协变与逆变(抗变)
  • 利用jquery编写加法运算验证码
  • 两列自适应布局方案整理
  • 聊一聊前端的监控
  • 漫谈开发设计中的一些“原则”及“设计哲学”
  • 我有几个粽子,和一个故事
  • 策略 : 一文教你成为人工智能(AI)领域专家
  • ​一文看懂数据清洗:缺失值、异常值和重复值的处理
  • #etcd#安装时出错
  • #QT(串口助手-界面)
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • #我与Java虚拟机的故事#连载13:有这本书就够了
  • (1)(1.13) SiK无线电高级配置(六)
  • (2)nginx 安装、启停
  • (20050108)又读《平凡的世界》
  • (done) NLP “bag-of-words“ 方法 (带有二元分类和多元分类两个例子)词袋模型、BoW
  • (LeetCode) T14. Longest Common Prefix
  • (附源码)ssm高校升本考试管理系统 毕业设计 201631
  • (心得)获取一个数二进制序列中所有的偶数位和奇数位, 分别输出二进制序列。
  • (转)es进行聚合操作时提示Fielddata is disabled on text fields by default
  • .naturalWidth 和naturalHeight属性,
  • .NET Core MongoDB数据仓储和工作单元模式封装
  • .NET Core 和 .NET Framework 中的 MEF2
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .NET分布式缓存Memcached从入门到实战
  • .NET建议使用的大小写命名原则