java多线程之批量操作

第一次写博客,工作一年多,属于新手类型,错误和不足之处大家多多提醒,谢谢啦。

作用简介:

 最直观的效果就是大大减少了操作时间。

1.首先建立测试实体类

package com.ncq.entity;

import java.io.Serializable;

public class Student implements Serializable{
	private static final long serialVersionUID = 1L;
	private Long id;
	private String name;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
2.建立实现业务的类

package com.ncq.service.impl;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.ncq.entity.Student;
import com.ncq.service.TestService;

public class TestServiceImpl implements TestService{
	
	private ExecutorService executor = Executors.newFixedThreadPool(10);//给定线程池数量
	
	private static final int MAX_DEAL = 50;//对多数据进行分组,50条一组,一组使用一个线程进行执行
	
	@Override
	public void addList(List list) {
		//判断数据是否为空
		if(list == null || list.isEmpty()){
			return;
		}
		int times = (list.size() + MAX_DEAL - 1) / MAX_DEAL;
        CountDownLatch countDownLatch = new CountDownLatch(times);//一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
        try {
        	 for (int i = 0; i < times; i++) {
                 if (i == times - 1) {
                 	executor.execute(new addListRunnable(list.subList(i * MAX_DEAL, list.size()), countDownLatch));//调用业务逻辑
                 } else {
                 	executor.execute(new addListRunnable(list.subList(i * MAX_DEAL, (i + 1) * MAX_DEAL), countDownLatch));
                 }
             }
             countDownLatch.await();//一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行
		} catch (Exception e) {
			e.printStackTrace();
		}
       
	}
	
	private class addListRunnable implements Runnable{

		private List list;
		private CountDownLatch countDownLatch;
		
		public addListRunnable(List list,CountDownLatch countDownLatch){
			super();
			this.list = list;
			this.countDownLatch = countDownLatch;
		}
		
		
		@Override
		public void run() {
			try {
				//模拟业务执行,这里并没有对list进行操作
				Thread.sleep(1000);
				System.out.println("当前线程为"+Thread.currentThread().getId());//输出当前线程id
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
                countDownLatch.countDown();//完成一次操作,计数减一  
            }
			
		}
		
	}
}

3.测试main方法 
  

package com.ncq.test;

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

import com.ncq.entity.Student;
import com.ncq.service.impl.TestServiceImpl;


public class Main {
	public static void main(String[] args) {
		List list = new ArrayList();
		for (int i = 0; i < 1010; i++) {
			Student stu = new Student();
			stu.setId(Long.valueOf(i));
			stu.setName("张三"+i);
			list.add(stu);
		}
		
		
		TestServiceImpl s = new TestServiceImpl();
		s.addList(list);
		System.out.println("==执行了完成==");
	}
}
写完收工,不足的地方请大牛指导


你可能感兴趣的:(多线程)