1、有20个账户,每个账户初始10000元。
2、有10个转账线程,从20个账户中随机抽取2个进行转账,转账金额为100以内随机的正整数。
3、每个线程转账100次。
4、请打印转账结束后所有账户的金额。
我的解决思路是用juc下的CopyOnWriteArrayList,存储每个账户,账户的金额用AtomicInteger赋值,保证原子性。再自定义个简单线程池(阻塞队列参数用的是LinkedBlockingQueue,要设置队列大小,默认值是Integer.MAX_VALUE,可能会堆积大量的请求,从而导致 OOM),10个转账线程转账100次,每次随机获取两个账户时,要注意随机获取的账户是否是同一个。转账完成后,打印即可。
代码演示import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class zhCache{
CopyOnWriteArrayList list = new CopyOnWriteArrayList<>(new ArrayList<>(20));
public AtomicInteger setNumber(){
AtomicInteger atomicInteger = new AtomicInteger(10000);
return atomicInteger;
}
}
public class ThreadStudyDemo {
public static void main(String[] args) {
//初始化CountDownLatch 计数器的值
final CountDownLatch countDownLatch = new CountDownLatch(10);
zhCache zhCache = new zhCache();
for(int i=0;i<20;i++){
zhCache.list.add(zhCache.setNumber());
}
System.out.println(zhCache.list);
//自定义简单线程池,设置最多放10个线程
ExecutorService threadPool=new ThreadPoolExecutor(
5,
10,
2L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(5),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy()//如果线程满了,教给主线程执行
);
try {
for (int j = 1; j <= 10; j++) {
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"开始执行任务");
for(int i=1;i<=100;i++){
int m1 = new Random().nextInt(20);
int m2 = new Random().nextInt(20);
//防止获取的是同一个账户
while (m1==m2){
m2=new Random().nextInt(20);
}
AtomicInteger atomicInteger1 = zhCache.list.get(m1);
AtomicInteger atomicInteger2 = zhCache.list.get(m2);
int n1 = new Random().nextInt(99) + 1;
atomicInteger1.addAndGet(n1);
atomicInteger2.addAndGet(-n1);
}
countDownLatch.countDown();
});
}
}catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
try {
// System.out.println(Thread.currentThread().getName()+"睡5秒");
// TimeUnit.SECONDS.sleep(5);
countDownLatch.await();
}catch (Exception e){
e.printStackTrace();
}
int count=0;
for (int i = 0; i < 20; i++) {
AtomicInteger atomicInteger = zhCache.list.get(i);
System.out.println("第"+(i+1)+"个账户金额为:"+atomicInteger);
count=atomicInteger.addAndGet(count);
}
System.out.println();
System.out.println("20个账户总金额为:"+count);
}
}
运行结果
这只是提供一下自己的思路和解决办法,有什么没考虑到位或者有问题的地方,欢迎大家指正,谢谢!也欢迎大家说出看法,提供自己解题思路,互相学习。



