java 多執行緒匯入資料__java

來源:互聯網
上載者:User
package cn.text;


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


public class Text {



//測試
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
//資料越大線程越多
for (int i = 0; i < 3000000; i++) {
list.add("hello"+i);
}
try {
exec(list);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void exec(List<String> list) throws InterruptedException{
int count = 300;//一個線程處理300條資料
int listSize = list.size();//資料集合大小
int runSize = (listSize/count)+1; //開啟的線程數
List<String> newlist = null;//存放每個線程的執行資料
ExecutorService executor = Executors.newFixedThreadPool(runSize);//建立一個線程池,數量和開啟線程的數量一樣
//建立兩個個計數器
CountDownLatch begin = new CountDownLatch(1);
CountDownLatch end = new CountDownLatch(runSize);
//迴圈建立線程
for (int i = 0; i < runSize ; i++) {
//計算每個線程執行的資料
if((i+1)==runSize){
int startIndex = (i*count);
int endIndex = list.size();
newlist= list.subList(startIndex, endIndex);
}else{
int startIndex = (i*count);
int endIndex = (i+1)*count;
newlist= list.subList(startIndex, endIndex);
}
//線程類
MyThread mythead = new MyThread(newlist,begin,end);
//這裡執行線程的方式是調用線程池裡的executor.execute(mythead)方法。
executor.execute(mythead);
}

begin.countDown();
end.await();

//執行完關閉線程池
executor.shutdown();
}
//線程類就不另外寫了,寫在同一個檔案裡咯,有需要可以分開寫
private static class MyThread implements Runnable{
private List<String> list;
private CountDownLatch begin;
private CountDownLatch end;

//建立個建構函式初始化 list,和其他用到的參數
public MyThread(List<String> list,CountDownLatch begin,CountDownLatch end){
this.list = list;
this.begin = begin;
this.end = end;
}

@Override
public void run() {
try {
for (int i = 0; i < list.size(); i++) {
//這裡還要說一下,,由於在實質項目中,當處理的資料存在等待逾時和出錯會使線程一直處於等待狀態
//這裡只是處理簡單的,
System.out.println(list.get(i));
}
//....
//執行完讓線程直接進入等待
begin.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//這裡要主要了,當一個線程執行完 了計數要減一不要這個線程會被一直掛起
//,end.countDown(),這個方法就是直接把計數器減一的
end.countDown();
}
}


}



}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.