JAVA动态打开多个线程

来源:互联网 发布:中国网络女主播排名 编辑:程序博客网 时间:2024/06/06 02:24
 //多线程保存在线数据
 public boolean invokeThreadMethod(List list){
  int num = 1000;   //定 义每个线程执行的数据量
  List thdList = null;
  Thread thread = null;
  boolean flag = false;  
  
  //根据数据量确定开多少个线程  
  int temp = list.size()/num;
  int begin = 0;
  int end = 0;
  
  //判断数据量是否小于num
  if(temp == 0){
   thread = new Thread(new MyThread(list));
   MyThread.threadList.add(thread);
   thread.start();
  }
  
  //根据数据量动态打开多线程
  for(int i=0;i<temp;i++){
   begin = i*num;
   
   if(i == (temp-1)){
    end = list.size();
   }else{
    end = i*num+num;
   }
   thdList = new ArrayList();
   for(int j=begin;j<end;j++){
    thdList.add((Httz)list.get(j));
   }
   thread = new Thread(new MyThread(thdList));
   MyThread.threadList.add(thread);
   thread.start();
  }
  
  //判断所有线程是否都执行完毕
  while (true) {
   List<Thread> threadList = MyThread.threadList;
   for(int i=0;i<threadList.size();i++){
    if(!((Thread)threadList.get(i)).isAlive()){
     threadList.remove(i);
    }
   }   
   
   if(threadList.size()==0){
    flag = true;
    break;
   }
  }  
  return flag;
 }