java多线程读取、操作List集合

import java.util.ArrayList;

import  java.util.List;
import  org.apache.commons.lang3.ArrayUtils;
 
public  class  Test_4 {
     /**
      * 多线程处理list
     
      * @param data  数据list
      * @param threadNum  线程数
      */
     public  synchronized  void  handleList(List<string> data,  int  threadNum) {</string>
         int  length = data.size();
         int  tl = length % threadNum ==  0  ? length / threadNum : (length
                 / threadNum +  1 );
 
         for  ( int  i =  0 ; i < threadNum; i++) {
             int  end = (i +  1 ) * tl;
             HandleThread thread =  new  HandleThread( "线程["  + (i +  1 ) +  "] " ,  data, i * tl, end > length ? length : end);
             thread.start();
         }
     }
 
     class  HandleThread  extends  Thread {
         private  String threadName;
         private  List<string> data;</string>
         private  int  start;
         private  int  end;
 
         public  HandleThread(String threadName, List<string> data,  int  start,  int  end) {</string>
             this .threadName = threadName;
             this .data = data;
             this .start = start;
             this .end = end;
         }
 
         public  void  run() {
             // TODO 这里处理数据
             data.subList(start, end).add( "^&*" );
             System.out.println(threadName)
         }
 
     }
 
     public  static  void  main(String[] args) {
         Test_4 test =  new  Test_4();
         // 准备数据
         List<string> data =  new  ArrayList<string>();</string></string>
         for  ( int  i =  0 ; i <  5000 ; i++) {
             data.add( "item"  + i);
         }
         test.handleList(data,  5 );
         System.out.println(ArrayUtils.toString(data));
     }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的多线程处理List集合通常用于提高程序的并发性能和资源利用率。多线程可以同时执行多个任务,而List集合提供了有序的数据结构,适合在并发环境中进行读写操作。以下是使用多线程处理List的一些关键点: 1. **线程安全**:对于List集合,如果要在多线程环境下直接修改(如添加、删除元素),应使用`Collections.synchronizedList(list)`确保线程安全,这样每次修改都会自动同步。 2. **CopyOnWriteArrayList**:`CopyOnWriteArrayList`是一个线程安全的列表实现,当线程试图修改时,会创建一个新的列表副本进行修改,避免了同步带来的性能开销,但不适合频繁的随机访问。 3. **并发包的工具类**:`java.util.concurrent`包中提供了`ConcurrentHashMap`和`BlockingQueue`等线程安全的数据结构,这些可以用来配合多线程操作List,例如用`BlockingQueue`作为缓冲区,处理线程间的数据交换。 4. **线程池**:使用`ExecutorService`或`ThreadPoolExecutor`创建线程池可以更好地管理并发任务,确保资源的有效利用,并可以通过设置线程池大小控制并发程度。 5. **线程同步**:如果需要多个线程同时读取但只修改一个线程的List,可以使用`synchronized`关键字对特定范围内的代码块进行同步,防止数据冲突。 6. **原子操作**:`AtomicInteger`, `AtomicLong`等原子类可以在多线程环境中保证操作的原子性,对于List的索引更新等场景很有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值