1. 程式人生 > >java多執行緒之批量操作

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<Student> 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<Student> list;
		private CountDownLatch countDownLatch;
		
		public addListRunnable(List<Student> 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();//完成一次操作,計數減一  
            }
			
		}
		
	}
}

</pre><p></p><pre>
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<Student> list = new ArrayList<Student>();
		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("==執行了完成==");
	}
}
寫完收工,不足的地方請大牛指導