有没有其他方法可以启用多线程而不使用我的下面代码中的Join

时间:2016-06-06 14:12:54

标签: java multithreading

目前我正在使用join()加入我当前的帖子。据我所知,join将使它成为简单的顺序代码。我想在多线程中做到这一点。

public class A {

private static final Logger logger = LoggerFactory.getLogger(A.class);

@Value("${query.interval}")
private String queryInterval;

private Set<B> missingKeys = new HashSet<>();
private Map<E, String> erroredKeys;

public Map<B, Collection<Product>> methodA(
        List<B> searchKeyList) {

    long startTime = System.currentTimeMillis();        
    missingKeys = new HashSet<>();
    erroredKeys = new HashMap<>();
    int size = searchKeyList.size();
    int threadNumber = 0;
    int startIndex = 0;
    int endIndex = 0;
    List<C> c = new ArrayList<>();

    int qrySize = Integer.parseInt(queryInterval);

    logger.info("Size of searchKeyList [{}] of instrument look up", new Object[] { searchKeyList.size() });
    for (; threadNumber < size / rdsQrySize; threadNumber++) {

        startIndex = threadNumber * rdsQrySize;
        endIndex = startIndex + rdsQrySize;

        logger.debug("Creating thread for Instrument LookUp");
        c = createThread(threadNumber, startIndex, endIndex,
                searchKeyList, c);

    }

    if (size % rdsQrySize != 0) {

        startIndex = threadNumber * rdsQrySize;
        endIndex = startIndex + size % rdsQrySize;

        logger.debug("Creating EXTRA thread for Instrument LookUp");

        c = createThread(requestor, businessLine, resolutionEnum, threadNumber, startIndex, endIndex,
                searchKeyList, c);

    }

    // Here I don't want to use join. I am looking for any other way to do this
    // to make my code run in multithreaded way

    for (C lookUpThread : c) {
        try {
            lookUpThread.join();
        } catch (InterruptedException e) {

        }
    }

    Map<B, Collection<Product>> responseDataList = new HashMap<>();
    for (C lookUpThread : c) {

        Map<B, Collection<Product>> instrumentResponseData = lookUpThread.getInstrumentResponse()
                .getFoundData();
        missingKeys.addAll(lookUpThread.getInstrumentResponse().getMissingKeys());
        erroredKeys.putAll(lookUpThread.getInstrumentResponse().getErroredKeys());
        responseDataList.putAll(instrumentResponseData);

    }

    long stopTime = System.currentTimeMillis();

    logger.info(
            "[{}] milliseconds taken to fetch [{}] instruments from RDS divided in [{}] threads  ",
            new Object[] { stopTime - startTime,size,  c.size() });

    return responseDataList;

}

private List<C> createThread(int threadNumber, int startIndex, int endIndex,
        List<B> searchKeyList, List<C> c) {

    List<B> searchKeys = new ArrayList<>();
    for (; startIndex < endIndex; startIndex++) {
        searchKeys.add(searchKeyList.get(startIndex));
    }

    ProductRequest<B> request = new ProductRequest<>(
            searchKeys);

    logger.info("Creating  thread no [{}] for Instrument LookUp", new Object[]{threadNumber});
    C lookUpThread = new C("RDS Instrument Thread - " + threadNumber);
    lookUpThread.setRequest(request);
    lookUpThread.start();

    c.add(lookUpThread);


    return c;
}

public Set<B> getMissingKeys() {
    return missingKeys;
}

public void setMissingKeys(Set<B> missingKeys) {
    this.missingKeys = missingKeys;
}

public Map<E, String> getErroredKeys() {
    return erroredKeys;
}

public void setErroredKeys(Map<E, String> erroredKeys) {
    this.erroredKeys = erroredKeys;
}

// Inner class for thread


private class C extends Thread {

    ClientResponse<B, Product, E> instrumentResponse = null;
    ProductRequest<B> request = null;

    C(String name) {
        super.setName(name);
    }

    public void run() {
        long startTime = System.currentTimeMillis();
        instrumentResponse = rdsDao.getByKey(request);
        long stopTime = System.currentTimeMillis();

        logger.info("RDS responded in [{}] milliseconds for thread [{}] while Instrument Lookup",
                new Object[] { stopTime - startTime, super.getName() });

    }

    public void setInstrumentResponse(
            ClientResponse<B, Product, E> instrumentResponse) {
        this.instrumentResponse = instrumentResponse;
    }

    public ClientResponse<B, Product, E> getInstrumentResponse() {
        return instrumentResponse;
    }

    public void setRequest(ProductRequest<B> request) {
        this.request = request;
    }

    public ProductRequest<B> getRequest() {
        return request;
    }

}
}

1 个答案:

答案 0 :(得分:1)

您的代码同时运行(不是您提到的顺序)。

ThreadT.join() 会使当前主题等待 ThreadT 完成。

当您生成多个线程并加入主线程时,那些非主线程仍会同时运行(因为您在Thread.start()中调用createThread())。

如果您没有加入非主线程,那么您的主线程/方法将在其他非主线程完成之前完成,我想这对您来说是不合适的。