多个线程实现累加
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
*
* @ProjectName:Skeleton
* @PackageName:
* @Verson :0.1
* @CreateUser :Test
* @CreateDate :2014-7-27上午11:46:03
* @UseFor :
*/
public class MultiThreadAdd {
public static void main(String[] args) {
long begin = System.currentTimeMillis() ;
Map<String, Callable<String>> taskMap = new HashMap<String, Callable<String>>();
taskMap.put("Task: 1" ,
new TestMessageTask1("Task: " + 1,0,500000000));
taskMap.put("Task: 2",
new TestMessageTask1("Task: " + 2,500000001,1000000000));
taskMap.put("Task: 3",
new TestMessageTask1("Task: " + 3,1000000001,1500000000));
taskMap.put("Task: 3",
new TestMessageTask1("Task: " + 4,1500000001,2000000000));
MessageThreadPoolExecutor1 executor = new MessageThreadPoolExecutor1(3,
4, 3000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(2));
try {
Map<String, String> resultMap = executor.performTasks(taskMap);
long sum = 0 ;
for (String key : resultMap.keySet()) {
String temp = resultMap.get(key) ;
sum += Long.valueOf(temp.split("=")[1]);
}
System.out.println(" 最后执行的结果:"+sum);
System.out.println("线程所花时间---->"+(System.currentTimeMillis()-begin));
begin = System.currentTimeMillis() ;
long temp = 0 ;
for(long i=0;i<=2000000000;i++)
{
temp += i ;
}
System.out.println(temp);
System.out.println(System.currentTimeMillis()-begin);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
/**
*
* @CreateUser :Test
* @CreateDate :2014-7-25上午10:43:02
* @UseFor :
*/
class TestMessageTask1 implements Callable<String> {
private String name;
private long begin ;
private long end ;
public TestMessageTask1(String name,long begin,long end) {
this.name = name;
this.begin = begin ;
this.end = end ;
}
@Override
public String call() throws Exception {
System.out.println(name+" 执行中.......");
long sum = 0 ;
for (long i = begin; i <= end; i++) {
sum += i ;
}
return name + " completed."+" sum="+sum;
}
};
class MessageThreadPoolExecutor1 extends ThreadPoolExecutor {
// 把父类的构造函数全弄出来算了。。。
public MessageThreadPoolExecutor1(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
handler);
}
public MessageThreadPoolExecutor1(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory);
}
public MessageThreadPoolExecutor1(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public MessageThreadPoolExecutor1(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, handler);
}
// 定义了一个方法执行任务集合,用了泛型,表示结果类型由Callable类型的任务对象决定
public <T> Map<String, T> performTasks(Map<String, Callable<T>> taskMap)
throws InterruptedException {
if (taskMap == null || taskMap.isEmpty())
throw new NullPointerException();
Map<String, Future<T>> futureMap = new HashMap<String, Future<T>>();
Map<String, T> messageMap = new HashMap<String, T>();
boolean done = false;
try {
for (String key : taskMap.keySet()) {
/**
* 这里用了两种方式执行任务:execute与submit,建议翻翻API文档, 关于Future的get方法,没弄懂。。。
*/
futureMap.put(key, submit(taskMap.get(key)));
}
/**
* 再次遍历任务,逐个调用get方法,get方法会阻塞住直到任务完成,
* get方法返回一个结果,根据结果判断任务执行成功与否,这也是我没有看懂
* API的地方,那个submit方法明明说返回的Future对象如果成功它的get方法
* 返回null,但messageMap中的value是有的,不为null。。。
*
* 先提交任务 返回信息保存在Future里面
*/
for (String key : futureMap.keySet()) {
Future<T> f = futureMap.get(key);
try {
T result = f.get();
messageMap.put(key, result);
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}
done = true;
return messageMap;
} finally {
// 若上面出了异常没done,没做完的任务直接cancel
if (!done) {
for (String key : futureMap.keySet()) {
futureMap.get(key).cancel(true);
}
}
this.shutdown();
}
}
}
例子 2
/**
*
*/
package com.comtop.test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @ProjectName:Skeleton
* @PackageName:com.comtop.test
* @Verson :0.1
* @CreateUser :lanweixing
* @CreateDate :2014-9-3上午9:41:16
* @UseFor :
*/
public class DoThread {
public static void main(String[] args) {
List<Num> list = new ArrayList<Num>();
List<Message> result1 = new ArrayList<Message>();
List<Message> result = new ArrayList<Message>();
// ExecutorService pool = Executors.newCachedThreadPool() ;
//使用线程池处理
ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 4, 3000L,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(2));
for (int i = 0; i < 1000000; i++) {
list.add(new Num(i));
}
long begin = System.currentTimeMillis();
try {
//1000000条数据5个线程跑 每个线程跑集合中的一部分
for (int i = 0; i < 5; i++) {
result1 = pool.submit(
new Main4Thread(list, i * 200000, (i + 1) * 200000))
.get();
result.addAll(result1);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
pool.shutdown();
System.out.println("所用时间" + (System.currentTimeMillis() - begin));
System.out.println(result.size());
}
};
class Main4Thread implements Callable<List<Message>> {
private List<Num> num;
private int begin;
private int end;
/**
* @param num
*/
Main4Thread(List<Num> num, int begin, int end) {
super();
this.num = num;
this.begin = begin;
this.end = end;
}
@Override
public List<Message> call() throws Exception {
List<Message> msgList = new ArrayList<Message>();
for (int i = begin; i < end; i++) {
if (num.get(i).getAge() >= 500000) {
//线程逻辑处理
Message msg = new Message();
msg.setMsg(num.get(i).getAge() + " Too old");
msgList.add(msg);
}
}
System.out.println(Thread.currentThread().getName());
return msgList;
}
};
class Message {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
};
class Num {
private int age;
/**
* @param age
*/
Num(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
};
3.使用线程处理项目中的需求
需求:三个线程并行处理三个SQL语句查询
线程类
@Scope("prototype")
//线程类需要注解到spring中 不然无法使用具体DAO操作
@Service
public class MainExcutor implements Callable<List<XXXVO>> {
// 日志记录
private final static Logger logger = LoggerFactory
.getLogger(MainExcutor.class);
@Resource
private XXXDAO xxxDAO;
private XXXVO xxxVO;
public XXXVO getXXXVO() {
return xxxVO;
}
public void setXXXVO(XXXVO xxxVO) {
this.xxxVO = xxxVO;
}
MainExcutor() {
super();
}
@Override
public List<XXXVO> call() throws Exception {
logger.info(" 线程查询数据中。。。");
List<XXXVO> resultList = new ArrayList<XXXVO>();
resultList = this.xxxDAO
.queryXXXData(xxxVO);
logger.info(" 线程查询数据结束。。。");
return resultList;
}
};
XXXDAO代码片段
//三个线程实例
@Resource
private MainExcutor mainExcutor1;
@Resource
private MainExcutor mainExcutor2;
@Resource
private MainExcutor mainExcutor3;
Map<String, Callable<List<XXXVO>>> taskMap = new HashMap<String, Callable<List<XXXVO>>>();
// 三个参数对象各不相同
BeanCopier beanCopier = BeanCopier.create(XXXVO.class,
XXXVO.class, false);
XXXVO xxxVO02 = new XXXVO();
XXXVO xxxVO03 = new ElectricTopicVO();
beanCopier.copy(xxxVO, xxxVO02, null);
beanCopier.copy(xxxVO, xxxVO03 , null);
// 1 2 3
xxxVO.setType("1");
this.mainExcutor1.setXXXVO(xxxVO);
taskMap.put("Task1", this.mainExcutor1);
xxxVO02.setType("2");
this.mainExcutor2.setXXXVO(xxxVO02);
taskMap.put("Task2", this.mainExcutor2);
xxxVO03 .setType("3");
this.mainExcutor3.setXXXVO(xxxVO03);
taskMap.put("Task3", this.mainExcutor3);
MessageThreadPoolExecutor executor = new MessageThreadPoolExecutor(3,
4, 3000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(4));
try {
Map<String, List<XXXVO>> resultMap = executor
.performTasks(taskMap);
for (String key : resultMap.keySet()) {
tempList = resultMap.get(key);
resultList.addAll(tempList);
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
线程池实现类(实现并发执行的关键)
class MessageThreadPoolExecutor extends ThreadPoolExecutor {
// 把父类的构造函数全弄出来算了。。。
public MessageThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
handler);
}
public MessageThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory);
}
public MessageThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
public MessageThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit,
BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, handler);
}
// 线程池主要执行方法
public <T> Map<String, T> performTasks(Map<String, Callable<T>> taskMap)
throws InterruptedException {
// 无任务集合
if (taskMap == null || taskMap.isEmpty()) {
throw new NullPointerException();
}
Map<String, Future<T>> futureMap = new HashMap<String, Future<T>>();
Map<String, T> messageMap = new HashMap<String, T>();
boolean done = false;
try {
for (String key : taskMap.keySet()) {
futureMap.put(key, submit(taskMap.get(key)));
}
for (String key : futureMap.keySet()) {
Future<T> f = futureMap.get(key);
try {
T result = f.get();
messageMap.put(key, result);
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}
done = true;
return messageMap;
} finally {
if (!done) {
for (String key : futureMap.keySet()) {
futureMap.get(key).cancel(true);
}
}
this.shutdown();
}
}
};
多线程调用多线程
需要注意的是子线程的线程池需要调大到大于8否则会导致不同步
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
public class Test implements Callable<String> {
private static final MainPoolExecutor executor = new MainPoolExecutor(3,
4, 3000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(
10));
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Test() {
super();
}
public Test(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
System.out.println(name + " 开始!");
Thread.sleep(1000);
System.out.println(name + " 结束!");
return null;
}
public static void main(String[] args) {
SuperTest[] testArr = new SuperTest[] { new SuperTest("父线程1"),
new SuperTest("父线程2"), new SuperTest("父线程3") };
Map<String, Callable<String>> taskMap = new HashMap<String, Callable<String>>();
try {
for (SuperTest test : testArr) {
taskMap.put(String.valueOf(Math.random()), test);
}
executor.performTasks(taskMap);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
};
class SuperTest implements Callable<String> {
// 一共有9个线程所以 corePoolSize 和 maximumPoolSize得设置成大于等于9的数字 否则不同步
private static final MainPoolExecutor executor = new MainPoolExecutor(9,
9, 3000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(
10));
private String name;
public String getName() {
return name;
}
public SuperTest() {
super();
}
public SuperTest(String name) {
this.name = name;
}
@Override
public String call() {
Test[] testArr = new Test[] { new Test(name + " 子线程1"),
new Test(name + " 子线程2"), new Test(name + " 子线程3") };
Map<String, Callable<String>> taskMap = new HashMap<String, Callable<String>>();
for (Test test : testArr) {
taskMap.put(String.valueOf(Math.random()), test);
}
try {
executor.performTasks(taskMap);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
return null;
}
}
FutureTask不会阻塞主线程
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* FutureTask线程执行不会阻塞主线程
* @author Test
*
*/
public class NoInterruptTest implements Callable<String> {
private long longTime;
// 锁对象 需要放外部 否则
private final ReadWriteLock lock =new ReentrantReadWriteLock();
public long getLongTime() {
return longTime;
}
public void setLongTime(long longTime) {
this.longTime = longTime;
}
public NoInterruptTest() {
super();
}
public NoInterruptTest(long longTime) {
this.longTime = longTime;
}
@Override
public String call() throws Exception {
// synchronized 用于控制同一个对象的多个线程访问
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName()+" 开始!");
Thread.sleep(longTime);
System.out.println(Thread.currentThread().getName()+" 结束!");
lock.writeLock().unlock() ;
return "lanweixing";
}
public static void main(String[] args) throws Exception{
long n1 = System.currentTimeMillis() ;
NoInterruptTest callable1 = new NoInterruptTest(3000);
NoInterruptTest callable2 = new NoInterruptTest(3000);
ExecutorService executorService = Executors.newCachedThreadPool();
FutureTask<String> task1 = new FutureTask<String>(callable1);
FutureTask<String> task2 = new FutureTask<String>(callable1);
executorService.execute(task1);
executorService.execute(task2);
while(true)
{
if(task1.isDone() && task2.isDone())
{
// 获得线程执行结果
System.out.println(task1.get());
System.out.println("任务已处理。");
break ;
}
}
System.out.println((System.currentTimeMillis()-n1)/1000);
executorService.shutdown();
}
};