java多线程并发处理任务

本文通过一个获取某个区间内质数的例子来说明如何使用java进行多线程并发处理。


1 新建一个Math类:

package com.gm.executor_service_test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Math {
	private static final int MAX_THREAD_COUNT = 10;
	
	public static List getPrimeNumbers(Long start, Long end) {
		Long[] points = getPoints(start, end);
		
		List primeNumbers = new ArrayList();
		
		List>> futureTaskList = new ArrayList>>();
		ExecutorService excutorService = Executors.newFixedThreadPool(MAX_THREAD_COUNT);
		for (int i = 0; i < points.length - 1; i++) {
			FutureTask> futureTask = new FutureTask>(new GetPrimeTask(points[i], points[i + 1] - 1));
			futureTaskList.add(futureTask);
			excutorService.submit(futureTask);
		}
		
		for (FutureTask> futureTask : futureTaskList) {
			try {
				List partPrimeNumbers = futureTask.get();
				primeNumbers.addAll(partPrimeNumbers);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return primeNumbers;
	}
	
	public static boolean isPrimeNumber(Long num) {
		for (Long i = 2L; i <= num / 2; i++) {
			if (num % i == 0) {
				return false;
			}
		}
		
		return true;
	}
	
	private static Long[] getPoints(Long start, Long end) {
		Long[] points = new Long[MAX_THREAD_COUNT];
		
		for (int i = 0; i < MAX_THREAD_COUNT - 1; i++) {
			points[i] = start + (end - start) / (MAX_THREAD_COUNT - 1) * i;
		}
		points[MAX_THREAD_COUNT - 1] = end + 1;
		
		return points;
	}
}

说明:这里面有两个重要的类,一个是ExecutorService,可以认为是一个线程池,另外一个是FutureTask, 这个可以认为是可以加入线程池中的一个job,用来执行具体的任务。

在上面的代码中,我们将每一个FutureTask对象保存起来,最后加入到线程池后,遍历每一个FutureTask对象,通过该对象的get方法来获取这个job计算得到的结果,get方法在job完成任务后才会返回。


2 新建GetPrimeTask类:

package com.gm.executor_service_test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

public class GetPrimeTask implements Callable> {

	private Long start;
	private Long end;
	
	public GetPrimeTask(Long start, Long end) {
		this.start = start;
		this.end = end;
	}
	
	public List call() throws Exception {
		// TODO Auto-generated method stub
		List primeNumberList = new ArrayList();
		
		for (Long i = start; i <= end; i++) {
			if (Math.isPrimeNumber(i)) {
				primeNumberList.add(i);
			}
		}
		
		return primeNumberList;
	}

}

说明:必须要实现Callable接口。


3 测试:

package com.gm.executor_service_test;

import java.sql.Time;
import java.util.Calendar;
import java.util.List;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
    	System.out.println("start");
    	Long startTime = getCurTime();
    	
    	List primeNumberList = Math.getPrimeNumbers(200000L, 300000L);
    	
    	for (Long primeNumber : primeNumberList) {
    		System.out.println("" + primeNumber);
    	}
    	Long endTime = getCurTime();
    	
    	System.out.println("消耗时间:" + (endTime - startTime) + " ms");
    }
    
    private static Long getCurTime() {
    	Calendar c = Calendar.getInstance();
    	return c.getTimeInMillis();
    }
}


你可能感兴趣的:(java)