并行与并发
并行:多个机器同时执行
并发:一个机器分时执行
Future接口
定义了操作异步任务执行的一些方法,获取异步任务执行的结果,取消任务的执行,判断任务是否被取消,判断任务执行完毕。
多线程/有返回/异步任务
class MyThread2 implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("execute");
return "hello";
}
}
public class aa {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask=new FutureTask(new MyThread2());
System.out.println(futureTask.isDone());
futureTask.run();
System.out.println(futureTask.isDone());
System.out.println(futureTask.get());
}
}
使用线程池
public class FutureThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(3);
Long startTime=System.currentTimeMillis();
FutureTask<String> futureTask1 = new FutureTask<>(() -> {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
return "futureTask1 success";
});
threadPool.submit(futureTask1);
FutureTask<String> futureTask2 = new FutureTask<>(() -> {
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
return "futureTask1 success";
});
threadPool.submit(futureTask2);
try {
TimeUnit.MILLISECONDS.sleep(300);
} catch (Exception e) {
e.printStackTrace();
}
futureTask1.get();
futureTask2.get();
Long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
threadPool.shutdown();
}
}
问题:
-
假如果get放在主线程前面,会阻塞主线程。
get(long time,TimeUnit unit)
超时便抛出异常 -
轮询会导致CPU空转。
while(!futureTask.isDone()){
}
futureTask1.get();
注意:回调通知,便不需要轮询。
使用CompletableFuture,异步回调。
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(3);
CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName());
return "hello";
}, threadPool);
System.out.println(completableFuture.get());
}
}
public class CompletableFutureTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService threadPool = Executors.newFixedThreadPool(3);
CompletableFuture<String> step1 = CompletableFuture.supplyAsync(() -> {
System.out.println("step1 come in");
try {
sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("step1 run end");
return "step1";
},threadPool).whenComplete((v, e) -> {
if (e == null) {
System.out.println("步骤1 结束");
step2();
}
}).exceptionally(e -> {
e.printStackTrace();
return null;
});
System.out.println("主线程");
}
private static void step2() {
CompletableFuture<String> comeIn = CompletableFuture.supplyAsync(() -> {
System.out.println("step2 come in");
try {
sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("step2 run end");
return "step2";
});
try {
System.out.println(comeIn.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
电商比价需求:
public class MallTest {
static List<NetMall> list = Arrays.asList(new NetMall("jd"), new NetMall("dd"), new NetMall("tb"));
//public static List<String> getPrice(List<NetMall> list, String product) {
// return list.stream().map(netMall -> product + " in " + netMall.getNetMall() + " " + netMall.getPrice(product)).collect(Collectors.toList());
//}
public static List<String> getPrice(List<NetMall> list, String product) {
return list.stream()
.map(netMall -> CompletableFuture.supplyAsync(() -> product + " in " + netMall.getNetMall() + " " + netMall.calPrice(product)))
.collect(Collectors.toList())
.stream()
.map(t->t.join())
.collect(Collectors.toList());
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
long startTime = System.currentTimeMillis();
List<String> list1 = getPrice(list, "mysql");
for (String s : list1) {
System.out.println(s);
}
long endTime = System.currentTimeMillis();
System.out.println("执行时间:" + (endTime - startTime));
}
}
@Data
@AllArgsConstructor
class NetMall {
private String netMall;
public BigDecimal calPrice(String productName) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return BigDecimal.valueOf(ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0));
}
}
https://blog.csdn.net/dolpin_ink/article/details/125116590
标签:JUC,系列,String,System,面试,println,new,public,out From: https://www.cnblogs.com/handsometaoa/p/17420793.html