问题
I want to call 8 methods in a method.
2 methods inside of these 8 methods is one hole task, and the remaining 6 methods is another hole task.
I want to process these 2 tasks exactly at the same time as parallel.
As I know I can do it with threads. But to be honest either I couldn't see an example which is similar to my goal, or I couldn't understand the example if I've seen.
Could you briefly show me an example in order me to finish my goal?
Thanks,
回答1:
Somethings like this maybe:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(final String[] args) throws InterruptedException {
final ExecutorService pool = Executors.newFixedThreadPool(2);
pool.execute(() -> {
method1();
method2();
});
pool.execute(() -> {
method3();
/* ... */
method8();
});
pool.shutdown();
if (!pool.awaitTermination(1, TimeUnit.DAYS))
System.err.println("Pool did not terminate.");
}
}
回答2:
This can be done in many ways, for example by using shared Semaphore:
public static class Task implements Runnable {
Semaphore s;
String name;
public Task(Semaphore s, String name) {
this.s = s;
this.name = name;
}
@Override
public void run() {
System.out.println(name + " waiting");
try {
s.acquire(); // wait for permit
System.out.println(name + " continuing");
} catch (InterruptedException e) {
System.out.println("Interrupted while waiting");
}
}
}
In main code, use shared Semaphore
to synchronize:
Semaphore s = new Semaphore(0);
new Thread(new Task(s, "Task A")).start();
new Thread(new Task(s, "Task B")).start();
Thread.sleep(1000);
s.release(2); // release 2 permits to allow both threads continue
Output:
Task A waiting
Task B waiting
Task A continuing // after 1 second
Task B continuing
来源:https://stackoverflow.com/questions/30257369/processing-two-tasks-exactly-at-the-same-time-as-parallel-in-java