list = getList();// Optional.ofNullable(_线程顺序性">
赞
踩
Future在Java5就引入了。 优点:一定程度上让一个线程池内的任务异步执行了 缺点:传统回调最大的问题就是不能将控制流分离到不同的事件处理器中。例如主线程等待各个异步执行的线程返回的结果来做下一步操作,则必须阻塞在future.get()的地方等待结果返回。这时候又变成同步了。 CompletableFuture在Java8引入。 实现了Future和CompletionStage接口,保留了Future的优点,并且弥补了其不足。即异步的任务完成后,需要用其结果继续操作时,无需等待。可以直接通过thenAccept、thenApply、thenCompose等方式将前面异步处理的结果交给另外一个异步事件处理线程来处理。 可见,这种方式才是我们需要的异步处理。一个控制流的多个异步事件处理能无缝的连接在一起 CompletableFuture.runAsync(() -> {}).thenRun(() -> {}); CompletableFuture.runAsync(() -> {}).thenAccept(resultA -> {}); CompletableFuture.runAsync(() -> {}).thenApply(resultA -> "resultB"); CompletableFuture.supplyAsync(() -> "resultA").thenRun(() -> {}); CompletableFuture.supplyAsync(() -> "resultA").thenAccept(resultA -> {}); CompletableFuture.supplyAsync(() -> "resultA").thenApply(resultA -> resultA + " resultB"); CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { throw new RuntimeException(); }) .exceptionally(ex -> "errorResultA") .thenApply(resultA -> resultA + " resultB") .thenApply(resultB -> resultB + " resultC") .thenApply(resultC -> resultC + " resultD"); System.out.println(future.join()); CompletableFuture<String> cfA = CompletableFuture.supplyAsync(() -> "resultA"); CompletableFuture<String> cfB = CompletableFuture.supplyAsync(() -> "resultB"); cfA.thenAcceptBoth(cfB, (resultA, resultB) -> {}); cfA.thenCombine(cfB, (resultA, resultB) -> "result A + B"); cfA.runAfterBoth(cfB, () -> {}); CompletableFuture<String> cfA = CompletableFuture.supplyAsync(() -> "resultA"); cfA.thenAcceptBoth(CompletableFuture.supplyAsync(() -> "resultB"), (resultA, resultB) -> {}); public static CompletableFuture<Void> allOf(CompletableFuture<?>... cfs){...} public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {...} CompletableFuture cfA = CompletableFuture.supplyAsync(() -> "resultA"); CompletableFuture cfB = CompletableFuture.supplyAsync(() -> 123); CompletableFuture cfC = CompletableFuture.supplyAsync(() -> "resultC"); CompletableFuture<Void> future = CompletableFuture.allOf(cfA, cfB, cfC); // 所以这里的 join() 将阻塞,直到所有的任务执行结束 future.join(); CompletableFuture cfA = CompletableFuture.supplyAsync(() -> "resultA"); CompletableFuture cfB = CompletableFuture.supplyAsync(() -> 123); CompletableFuture cfC = CompletableFuture.supplyAsync(() -> "resultC"); CompletableFuture<Object> future = CompletableFuture.anyOf(cfA, cfB, cfC); Object result = future.join(); public void allOf(){ CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World"); CompletableFuture<Void> combinedFuture = CompletableFuture.allOf(future1, future2, future3); } public void join(){ CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello"); CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "Beautiful"); CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "World"); String combined = Stream.of(future1, future2, future3) .map(CompletableFuture::join) .collect(Collectors.joining(" ")); } public void handleError(){ String name = null; CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> { if (name == null) { throw new RuntimeException("Computation error!"); } return "Hello, " + name; }).handle((s, t) -> s != null ? s : "Hello, Stranger!"); }
public class ThreadOrderTest {
public static void main(String[] args) {
// String s = getKey();
// Optional.ofNullable(s).orElse("").length();
// List<String> list = getList();
// Optional.ofNullable(list).orElse(new ArrayList<>()).forEach(o -> {
// System.out.println(o);
// });
}
}
class ThreadJoinDemo { public static void main(String[] args) { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("产品经理规划新需求"); } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { thread1.join(); System.out.println("开发人员开发新需求功能"); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { try { thread2.join(); System.out.println("测试人员测试新功能"); } catch (InterruptedException e) { e.printStackTrace(); } } }); System.out.println("早上:"); System.out.println("测试人员来上班了..."); thread3.start(); System.out.println("产品经理来上班了..."); thread1.start(); System.out.println("开发人员来上班了..."); thread2.start(); } } class ThreadMainJoinDemo { public static void main(String[] args) throws Exception { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("产品经理正在规划新需求..."); } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { System.out.println("开发人员开发新需求功能"); } }); final Thread thread3 = new Thread(new Runnable() { @Override public void run() { System.out.println("测试人员测试新功能"); } }); System.out.println("早上:"); System.out.println("产品经理来上班了"); System.out.println("测试人员来上班了"); System.out.println("开发人员来上班了"); thread1.start(); //在父进程调用子进程的join()方法后,父进程需要等待子进程运行完再继续运行。 System.out.println("开发人员和测试人员休息会..."); thread1.join(); System.out.println("产品经理新需求规划完成!"); thread2.start(); System.out.println("测试人员休息会..."); thread2.join(); thread3.start(); } } class ThreadWaitDemo { private static Object myLock1 = new Object(); private static Object myLock2 = new Object(); /** * 为什么要加这两个标识状态? * 如果没有状态标识,当t1已经运行完了t2才运行,t2在等待t1唤醒导致t2永远处于等待状态 */ private static Boolean t1Run = false; private static Boolean t2Run = false; public static void main(String[] args) { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { synchronized (myLock1) { System.out.println("产品经理规划新需求..."); t1Run = true; myLock1.notify(); } } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { synchronized (myLock1) { try { if (!t1Run) { System.out.println("开发人员先休息会..."); myLock1.wait(); } synchronized (myLock2) { System.out.println("开发人员开发新需求功能"); myLock2.notify(); } } catch (InterruptedException e) { e.printStackTrace(); } } } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { synchronized (myLock2) { try { if (!t2Run) { System.out.println("测试人员先休息会..."); myLock2.wait(); } System.out.println("测试人员测试新功能"); } catch (InterruptedException e) { e.printStackTrace(); } } } }); System.out.println("早上:"); System.out.println("测试人员来上班了..."); thread3.start(); System.out.println("产品经理来上班了..."); thread1.start(); System.out.println("开发人员来上班了..."); thread2.start(); } } class ThreadPoolDemo { static ExecutorService executorService = Executors.newSingleThreadExecutor(); public static void main(String[] args) throws Exception { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("产品经理规划新需求"); } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { System.out.println("开发人员开发新需求功能"); } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { System.out.println("测试人员测试新功能"); } }); System.out.println("早上:"); System.out.println("产品经理来上班了"); System.out.println("测试人员来上班了"); System.out.println("开发人员来上班了"); System.out.println("领导吩咐:"); System.out.println("首先,产品经理规划新需求..."); executorService.submit(thread1); System.out.println("然后,开发人员开发新需求功能..."); executorService.submit(thread2); System.out.println("最后,测试人员测试新功能..."); executorService.submit(thread3); executorService.shutdown(); } } class ThreadConditionDemo { private static Lock lock = new ReentrantLock(); private static Condition condition1 = lock.newCondition(); private static Condition condition2 = lock.newCondition(); /** * 为什么要加这两个标识状态? * 如果没有状态标识,当t1已经运行完了t2才运行,t2在等待t1唤醒导致t2永远处于等待状态 */ private static Boolean t1Run = false; private static Boolean t2Run = false; public static void main(String[] args) { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { lock.lock(); System.out.println("产品经理规划新需求"); t1Run = true; condition1.signal(); lock.unlock(); } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { lock.lock(); try { if (!t1Run) { System.out.println("开发人员先休息会..."); condition1.await(); } System.out.println("开发人员开发新需求功能"); t2Run = true; condition2.signal(); } catch (InterruptedException e) { e.printStackTrace(); } lock.unlock(); } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { lock.lock(); try { if (!t2Run) { System.out.println("测试人员先休息会..."); condition2.await(); } System.out.println("测试人员测试新功能"); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } } }); System.out.println("早上:"); System.out.println("测试人员来上班了..."); thread3.start(); System.out.println("产品经理来上班了..."); thread1.start(); System.out.println("开发人员来上班了..."); thread2.start(); } } class ThreadCountDownLatchDemo { /** * 用于判断线程一是否执行,倒计时设置为1,执行后减1 */ private static CountDownLatch c1 = new CountDownLatch(1); /** * 用于判断线程二是否执行,倒计时设置为1,执行后减1 */ private static CountDownLatch c2 = new CountDownLatch(1); public static void main(String[] args) { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("产品经理规划新需求"); //对c1倒计时-1 c1.countDown(); } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { //等待c1倒计时,计时为0则往下运行 c1.await(); System.out.println("开发人员开发新需求功能"); //对c2倒计时-1 c2.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { try { //等待c2倒计时,计时为0则往下运行 c2.await(); System.out.println("测试人员测试新功能"); } catch (InterruptedException e) { e.printStackTrace(); } } }); System.out.println("早上:"); System.out.println("测试人员来上班了..."); thread3.start(); System.out.println("产品经理来上班了..."); thread1.start(); System.out.println("开发人员来上班了..."); thread2.start(); } } class CyclicBarrierDemo { static CyclicBarrier barrier1 = new CyclicBarrier(2); static CyclicBarrier barrier2 = new CyclicBarrier(2); public static void main(String[] args) { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { try { System.out.println("产品经理规划新需求"); //放开栅栏1 barrier1.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { //放开栅栏1 barrier1.await(); System.out.println("开发人员开发新需求功能"); //放开栅栏2 barrier2.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }); final Thread thread3 = new Thread(new Runnable() { @Override public void run() { try { //放开栅栏2 barrier2.await(); System.out.println("测试人员测试新功能"); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }); System.out.println("早上:"); System.out.println("测试人员来上班了..."); thread3.start(); System.out.println("产品经理来上班了..."); thread1.start(); System.out.println("开发人员来上班了..."); thread2.start(); } } class SemaphoreDemo { private static Semaphore semaphore1 = new Semaphore(1); private static Semaphore semaphore2 = new Semaphore(1); public static void main(String[] args) { final Thread thread1 = new Thread(new Runnable() { @Override public void run() { System.out.println("产品经理规划新需求"); semaphore1.release(); } }); final Thread thread2 = new Thread(new Runnable() { @Override public void run() { try { semaphore1.acquire(); System.out.println("开发人员开发新需求功能"); semaphore2.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread thread3 = new Thread(new Runnable() { @Override public void run() { try { semaphore2.acquire(); thread2.join(); semaphore2.release(); System.out.println("测试人员测试新功能"); } catch (InterruptedException e) { e.printStackTrace(); } } }); System.out.println("早上:"); System.out.println("测试人员来上班了..."); thread3.start(); System.out.println("产品经理来上班了..."); thread1.start(); System.out.println("开发人员来上班了..."); thread2.start(); } } class FutureTaskThread implements Callable { private String threadName; public FutureTaskThread(String threadName) { this.threadName = threadName; } public Object call() throws Exception { Thread.sleep(3000); return "线程" + threadName + "执行结束了"; } public static void main(String[] args) throws ExecutionException, InterruptedException { System.out.println("主线程开始等待子线程执行完成"); FutureTask taskA = new FutureTask(new FutureTaskThread("A")); FutureTask taskB = new FutureTask(new FutureTaskThread("B")); new Thread(taskA).start(); new Thread(taskB).start(); //判断子线程A是否执行结束 if (!taskA.isDone()) { System.out.println("线程A未执行完,主线程继续等待"); } //判断子线程B是否执行结束 if (!taskB.isDone()) { System.out.println("线程B未执行完,主线程继续等待"); } //打印一下线程A的返回值 System.out.println(taskA.get()); //打印一下线程B的返回值 System.out.println(taskB.get()); System.out.println("子线程执行完成了,主线程开始执行了"); } } class CountDownLatchThread implements Runnable { private String threadName; private CountDownLatch latch; public CountDownLatchThread(String threadName, CountDownLatch latch) { this.threadName = threadName; this.latch = latch; } public void run() { System.out.println("线程" + threadName + "开始工作"); try { //模拟线程工作 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("线程" + threadName + "完成工作"); latch.countDown(); } public static void main(String[] args) throws InterruptedException { //直接使用main线程作为主线程 // CountDownLatch latch = new CountDownLatch(2); // System.out.println("主线程需要等待子线程执行完成后再执行"); // Thread threadA = new Thread(new CountDownLatchThread("A", latch)); // Thread threadB = new Thread(new CountDownLatchThread("B", latch)); // threadA.start(); // threadB.start(); // latch.await(); // System.out.println("子线程执行完成了,主线程继续执行"); //创建主线程X Thread threadX = new Thread(new Runnable() { CountDownLatch latch = new CountDownLatch(2); public void run() { System.out.println("主线程需要等待子线程执行完成后再执行"); Thread threadA = new Thread(new CountDownLatchThread("A", latch)); Thread threadB = new Thread(new CountDownLatchThread("B", latch)); threadA.start(); threadB.start(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("子线程执行完成了,主线程继续执行"); } }); //启动主线程X threadX.start(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。