简体   繁体   中英

How to return a method when some threads in it have finished?

I create a ConcurrentHashMap, execute several sql queries at the same time and put the results into the map. Previously I used an AtomicInteger to calculate the number of finished task. One suggests me using Map.size() can be conciser. For example:

    final Map<String, Object> res = new ConcurrentHashMap<>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            res.put("first", 1);    // imagine this is the query result
        }
    }).run();
    new Thread(new Runnable() {
        @Override
        public void run() {
            res.put("second", 2);   // imagine this is the query result
        }
    }).run();
    new Thread(new Runnable() {
        @Override
        public void run() {
            res.put("third", 3);    // imagine this is the query result
        }
    }).run();
    while (true) {
        if (res.size() == 3) {
            break;
        }
    }
    return res;

Now the occupancy of CPU is high while the loop spins. Is there anyway better to return after the tasks finished?

Use CountDownLatch:

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

public class TestJava {

    public static void main(String[] args) throws Exception {
        final CountDownLatch cdl = new CountDownLatch(3);
        final Map<String, Object> res = new ConcurrentHashMap<>();
        new Thread(new Runnable() {
            @Override
            public void run() {
                res.put("first", 1);    // imagine this is the query result
                cdl.countDown();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                res.put("second", 2);   // imagine this is the query result
                cdl.countDown();
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                res.put("third", 3);    // imagine this is the query result
                cdl.countDown();
            }
        }).start();

        cdl.await();

        System.out.println("res size = " + res.size());

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM