线程池方式对数组多线程随机取出分析

题目是这样的:

使用 ThreadPool 线程池(线程池大小为 3)对一组数组 [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]每个线程只允许随机取出 1 个,取出后删除直 到数组为空,取出的结果重新放到另一数组中。 

我是这样思考的:

 线程安全实现方式有显示锁,同步块,volatile,处于性能考虑,选择顺序:volatile ,显示锁,同步块,

读取同一个数组,线程池的方式,需要线程共享,所以选择由Runnable接口实现,不是Thread类。

我的实现是这样的:

 实习测试遇到,有好的思路请小伙伴留言,请教学习

package pojo;

import java.util.Arrays;
import java.util.Random;

/**
 * @Description :
 * @Author: Liruilong
 * @Date: 2020/3/14 2:02
 */
public class ArrayOperate implements Runnable {

    private volatile int[] ints = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    private volatile int[] getInts = new int[16];
    public  volatile static int index = 0;

    @Override
    public  void run() {
        Random random = new Random();
        if (ints.length - index > 0) {
            int indexScope = ints.length - index;
            int indexs = random.nextInt(indexScope);
            getInts[index] = ints[indexs];
            ints[indexs] = ints[indexScope - 1];
            index++;
        }
    }
    public void print() {
        System.out.println("生成的数组为:" + Arrays.toString(getInts));
    }


}

 

package service;

import com.sun.corba.se.spi.orbutil.threadpool.ThreadPool;
import pojo.ArrayOperate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description :
 * @Author: Liruilong
 * @Date: 2020/3/14 1:51
 */
public class ArrayService {



    /**
     * @Author Liruilong
     * @Description  数组线程池操作
     * @Date 13:21 2020/3/14
     * @Param []
     * @return void
     **/

    public void randomArray() {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        ArrayOperate arrayOperate = new ArrayOperate();
        while (ArrayOperate.index < 16) {
                executorService.execute(arrayOperate);
        }
        arrayOperate.print();
    }
}

 

posted @ 2020-03-24 21:46  山河已无恙  阅读(527)  评论(0编辑  收藏  举报