多线程 各线程返回值控制

在网上看到很多同事问多线程时,获取子线程的返回值的问题,今天特意看了一下,其实JDK1.6里面已经完全支持了

不但可以控制子线程的返回值,对于子线程的超时时间和终止,取消等都支持

public List<Long> getIdList(ScoreDoc[] scoreDocs, IndexSearcher search)
            throws CorruptIndexException, IOException, InterruptedException, ExecutionException {
        final int records = 10000;
        int len = scoreDocs.length;
        List<ScoreDoc[]> scoreDocList = new ArrayList<ScoreDoc[]>(len);
        Map<String, FieldSelectorResult> fieldSelections = new HashMap<String, FieldSelectorResult>(
                1);
        fieldSelections.put("id", FieldSelectorResult.LOAD);
        FieldSelector fieldSelector = new MapFieldSelector(fieldSelections);
        int threadCount = len / records;
        int modCount = len % records;
        int srcPos = 0;
        if (threadCount > 0 && modCount != 0) {
            for (int i = 0; i < threadCount; i++) {
                ScoreDoc[] idsArry = new ScoreDoc[records];
                System.arraycopy(scoreDocs, srcPos, idsArry, 0, records);
                scoreDocList.add(idsArry);
                srcPos = srcPos + records;
            }
            ScoreDoc[] idsArry = new ScoreDoc[modCount];
            System.arraycopy(scoreDocs, srcPos, idsArry, 0, modCount);
            scoreDocList.add(idsArry);

        } else if (threadCount == 0 && modCount != 0) {
            ScoreDoc[] idsArry = new ScoreDoc[modCount];
            System.arraycopy(scoreDocs, 0, idsArry, 0, modCount);
            scoreDocList.add(idsArry);
        }

        Executor executor = Executors.newFixedThreadPool(scoreDocList.size());
        List<Long> ids = new ArrayList<Long>(len);
        for (int i = 0; i < scoreDocList.size(); i++) {
            FutureTask<List<Long>> task = new FutureTask<List<Long>>(new ReadDoc(
                    scoreDocList.get(i), search, fieldSelector));
            executor.execute(task);
            ids.addAll(task.get());
        }

        return ids;
    }

//线程实现类
    class ReadDoc implements Callable<List<Long>> {
        private ScoreDoc[]    scoreDocs;
        private IndexSearcher search;
        private FieldSelector fieldSelector;

        public ReadDoc(ScoreDoc[] scoreDocs, IndexSearcher search, FieldSelector fieldSelector) {
            this.scoreDocs = scoreDocs;
            this.search = search;
            this.fieldSelector = fieldSelector;
        }

        /*
         * (non-Javadoc)
         * @see java.util.concurrent.Callable#call()
         */
        @Override
        public List<Long> call() throws Exception {
            List<Long> ids = new ArrayList<Long>();
        获取ID集合
            for (int i = 0; i < scoreDocs.length; i++) {
                Document doc = search.doc(scoreDocs[i].doc, fieldSelector);
                ids.add(Long.valueOf(doc.getFieldable("id").stringValue()));
            }
            return ids;
        }
    }

你可能感兴趣的:(多线程,线程返回值,线程终止,线程取消)