我需要在Java中为我所在的类创建一个程序,但我需要能够同时执行6个方法。我不知道如何解决这个问题,但这里只是我的一小部分内容:
public static void main(String[] args) {
method1();
method2();
method3();
method4();
method5();
method6();
}
这只是一次播放一个方法,我需要一次完成所有方法。
答案 0 :(得分:9)
使用多个线程,但如果您要从多个线程编辑相同的对象,则应该阅读并发性。
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();
}
答案 1 :(得分:1)
正如@ kevin-cruijssen所说,你可以使用这样的东西:
public static void main(String[] args) {
Arrays.asList(new Thread(() -> method1()), new Thread(() -> method2()))
.parallelStream().forEach(x -> x.start());
}
但您无法保证执行顺序。
答案 2 :(得分:0)
如果您的计算机具有6个CPU,则可以实现此操作的完整示例
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();
}
}