Reputation: 95
I need to make a program in Java for a class I am in, but I need to be able to make 6 methods execute at once. I have no idea how to go about this, but here is a small bit of what I have:
public static void main(String[] args) {
method1();
method2();
method3();
method4();
method5();
method6();
}
This just plays the methods one at a time, and I need them all at once.
Upvotes: 1
Views: 13848
Reputation: 31
An full example of how to do this can be achieved if your machine has 6CPU
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class demo {
private int count1 = 0;
private int count2 = 0;
private int count3 = 0;
private int count4 = 0;
private int count5 = 0;
private int count6 = 0;
int countA() {
for (int i = 0; i < 1000; i++) {
count1++;
}
System.out.println(count1);
return count1;
}
int countB() {
for (int i = 0; i < 1000; i++) {
count2++;
}
System.out.println(count2);
return count2;
}
int countC() {
for (int i = 0; i < 1000; i++) {
count3++;
}
System.out.println(count3);
return count3;
}
int countD() {
for (int i = 0; i < 1000; i++) {
count4++;
}
System.out.println(count4);
return count4;
}
int countE() {
for (int i = 0; i < 1000; i++) {
count5++;
}
System.out.println(count5);
return count5;
}
int countF() {
for (int i = 0; i < 1000; i++) {
count6++;
}
System.out.println(count6);
return count6;
}
public void execute() {
ExecutorService executorService = Executors.newFixedThreadPool(6);
// method reference introduced in Java 8
executorService.submit(this::countA);
executorService.submit(this::countB);
executorService.submit(this::countC);
executorService.submit(this::countD);
executorService.submit(this::countE);
executorService.submit(this::countF);
// close executorService
executorService.shutdown();
}
public static void main(String[] args) {
new demo().execute();
}
}
Upvotes: 1
Reputation: 1181
As @kevin-cruijssen said you can use something like this:
public static void main(String[] args) {
Arrays.asList(new Thread(() -> method1()), new Thread(() -> method2()))
.parallelStream().forEach(x -> x.start());
}
But you have no guarantee on the execution order.
Upvotes: 2
Reputation: 11093
Make use of multiple threads, although you should read up on concurrency if you're going to edit the same objects from multiple threads.
public static void main(String[] args) {
new Thread() {
public void run() {
method1();
}
}.start();
new Thread() {
public void run() {
method2();
}
}.start();
//etc
//or, as kingdamian42 pointed out, if you use java8, use this
new Thread(() -> method1()).start();
new Thread(() -> method2()).start();
}
Upvotes: 11