G
G
gibsonen2019-05-15 12:19:50
Java
gibsonen, 2019-05-15 12:19:50

How to correctly form multithreading?

Please tell me the best way to do it in my case. I want to parallelize tasks, but it turns out with only 1 thread. Constantly need to wait when I get the result d (future.get()). Is it possible to somehow make it so that the thread that is waiting for the result remains waiting, and the other thread continues to do its work further along the cycle?

List<Integer> index = new ArrayList<>();
        ///....///
        List<List<Integer>> dis = new ArrayList<>();
        for (int i = 0; i < links.size() - 1; i++) {
            if (index.get(i) == 0) {
                ..////...
                List<Integer> list = new ArrayList<>();
                for (int j = i + 1; j < links.size(); j++) {

                        URL oneURL = new URL(links.get(i));           
                        URL twoURL = new URL(links.get(j));
                        Task task = new Task(oneURL, twoURL);
                        ExecutorService executor = Executors.newFixedThreadPool(1);
                        Future<Double> future = executor.submit(task);
                        Double d = future.get();
                        executor.shutdown();
                        if (d > k) {
                            list.add(j);
                            index.set(j, 1);
                        }
                }
                dis.add(list);
            }
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2019-05-15
@zagayevskiy

In this form, it's all completely useless. Creating a thread is an expensive operation.
In order for this to work, you need to create an executor once, and submit different tasks to it. After the cycle, wait for them. Accordingly, the loop body should not depend on the result of the task execution.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question