Don*_*llo 2 java multithreading java-8 completable-future
我正在测试如何CompletableFuture
工作。我对如何并行执行任务感兴趣:
try {
CompletableFuture one = CompletableFuture.runAsync(() -> {
throw new RuntimeException("error");
});
CompletableFuture two = CompletableFuture.runAsync(() -> System.out.println("2"));
CompletableFuture three = CompletableFuture.runAsync(() -> System.out.println("3"));
CompletableFuture all = CompletableFuture.allOf(one, two, three);
all.get();
} catch (InterruptedException e) {
System.out.println(e);
} catch (ExecutionException e) {
System.out.println(e);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,他们将全部被处决。
1 . 当其中一个线程出现异常时,是否可以中断所有正在运行的线程?
2 . 当此代码位于可以从不同线程调用的类方法内部时,它是线程安全的吗?
1.当其中一个线程出现异常时,是否可以中断所有正在运行的线程?
对的,这是可能的。所有线程都应该有权访问公共对象,该对象的状态可以由其他线程更改和读取。可以是例如AtomicInteger
。请参见下面的示例:
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
public class Dates {
public static void main(String[] args) throws Exception {
try {
AtomicInteger excCounter = new AtomicInteger(0);
CompletableFuture one = CompletableFuture.runAsync(new ExcRunnable(excCounter));
CompletableFuture two = CompletableFuture.runAsync(new PrintRunnable("2", excCounter));
CompletableFuture three = CompletableFuture.runAsync(new PrintRunnable("3", excCounter));
CompletableFuture all = CompletableFuture.allOf(one, two, three);
all.get();
} catch (InterruptedException | ExecutionException e) {
System.out.println(e);
}
}
}
class ExcRunnable implements Runnable {
private final AtomicInteger excCounter;
public ExcRunnable(AtomicInteger excCounter) {
this.excCounter = excCounter;
}
@Override
public void run() {
Random random = new Random();
int millis = (int) (random.nextDouble() * 5000);
System.out.println("Wait " + millis);
Threads.sleep(450);
// Inform another threads that exc occurred
excCounter.incrementAndGet();
throw new RuntimeException("error");
}
}
class PrintRunnable implements Runnable {
private final String name;
private final AtomicInteger excCounter;
public PrintRunnable(String name, AtomicInteger excCounter) {
this.name = name;
this.excCounter = excCounter;
}
@Override
public void run() {
int counter = 10;
while (counter-- > 0 && excCounter.get() == 0) {
System.out.println(name);
Threads.sleep(450);
}
}
}
class Threads {
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我们有 3 个任务:两个打印它的名称,一个在一段时间后抛出异常。在引发异常之前,计数器会增加,以通知其他任务其中一个任务失败并且它们应该完成执行。打印作业正在检查此计数器,如果不满足条件,它们就会完成其作业。当您注释excCounter.incrementAndGet();
行时,其他任务完成了他们的工作,而不知道其中一个任务抛出了异常。
- 当此代码位于可以从不同线程调用的类方法内部时,它是线程安全的吗?
看一下线程安全的定义。例如,假设打印任务随着每个打印行而增加公共计数器。如果计数器是原始的,int
则它不是线程安全的,因为计数器值可以被替换。但如果你使用AtomicInteger
它是线程安全的,因为AtomicInteger
它是线程安全的。