多线程解决方案
- 两种方式
- synchronized:线程共享数据同步
- Threadlocal:线程因并发产生数据不一致问题
- 区别
- synchronized采取锁机制,数据共享
- Threadlocal 提供数据副本,数据隔离
线程池
在一个多线程用于程序中创建一个线程集合,需要执行新任务时进行线程复用,不需要大量的创建销毁过程,节省资源和时间。
优点
- 降低资源消耗
- 提高响应速度
- 提高线程可管理性
/**
*源码
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}
*/
//线程池创建的简单示例
public static void main(String[] args){
int count=200000;//队列数
long StartTime=System.currentTimeMillis();//开始时间
final List<Integer> l=new LinkedList<>();
ThreadPoolExecutor tp=new ThreadPoolExecutor(1,1,60, TimeUnit.SECONDS,
new LinkedBlockingDeque<Runnable>(count));//创建线程池
final Random random=new Random();
for (int i = 0; i <count ; i++) {
tp.execute(new Runnable() {
@Override
public void run() {
l.add(random.nextInt());//将随机数加入线程
}
});
}
tp.shutdown();
try {
tp.awaitTermination(1,TimeUnit.DAYS);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()-StartTime);//结束时间
System.out.println(l.size());
}