gpt4 book ai didi

java - Java CompletableFuture和线程

转载 作者:行者123 更新时间:2023-12-03 12:59:05 25 4
gpt4 key购买 nike

我想使用异步模式使用CompletableFuture Java 8-9启动线程,这些是我的类和线程:

我有3个线程。我的类(class)只包含一个方法myMethod()

Class_1 class_1 = new Class_1();

Class_2 class_2 = new Class_2();

Class_3 class_3 = new Class_3();

设置我的 Runnable如下:
Runnable runnableClass_1 = new Runnable(){
public void run(){
class_1.myMethod();
try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); }
}
};

Runnable runnableClass_2 = new Runnable(){
public void run(){
class_2.myMethod();
try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); }
}
};

Runnable runnableClass_3 = new Runnable(){
public void run(){
class_3.myMethod();
try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); }
}
};

创建线程:
Thread t_1 = new Thread( runnableClass_1 );

Thread t_2 = new Thread( runnableClass_2 );

Thread t_3 = new Thread( runnableClass_3 );

最后,我的问题是如何使用 CompletableFuture异步模式启动这三个线程。

最佳答案

这是实现相同方法的方法:

List<String> results = new ArrayList<String>();

CompletableFuture<Void> run1 = CompletableFuture.runAsync(() -> {
pauseSeconds(2);
results.add("first task");
}, service);

CompletableFuture<Void> run2 = CompletableFuture.runAsync(() -> {
pauseSeconds(3);
results.add("second task");
}, service);

CompletableFuture<Void> finisher = run1.runAfterBothAsync(run2,
() -> results.add(results.get(0)+ "&"+results.get(1)),service);
pauseSeconds(4);
System.out.println("finisher.isDone() = "+finisher.isDone());
System.out.println("results.get(2) = "+results.get(2));
// assert(finisher.isDone(), is(true));
// assertThat(results.get(2),is("first task&second task"));
}

public static void pauseSeconds(int num){
try {
Thread.sleep(num);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

关于java - Java CompletableFuture和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50907862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com