package tongbu;
public class JoinDemo {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("你好1");
});
Thread thread1 = new Thread(() -> {
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("你好2");
});
Thread thread2 = new Thread(() -> {
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("你好3");
});
thread.start();
thread1.start();
thread2.start();
}
}
运行结果:
package tongbu;
import java.util.concurrent.CountDownLatch;
/**
* @author: dlwlrma
* @data 2025年05月31日 17:14
* @Description
*/
public class CountDownLattchDemo {
public static void main(String[] args) {
CountDownLatch latch1 = new CountDownLatch(1);
CountDownLatch latch2 = new CountDownLatch(1);
Thread thread = new Thread(() -> {
System.out.println("你好1");
//释放
latch1.countDown();
});
Thread thread1 = new Thread(() -> {
try {
latch1.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("你好2");
latch2.countDown();
});
Thread thread2 = new Thread(() -> {
try {
latch2.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("你好3");
});
thread.start();
thread1.start();
thread2.start();
}
}
运行结果同上
任务一执行完毕后之后执行任务二,任务三和任务一任务二一起执行,所有任务都有返回值,等任务二和任务三都执行完成后,在执行任务四
package yibu;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
/**
* @author: dlwlrma
* @data 2025年05月31日 18:26
* @Description
* 任务描述:任务一执行完毕后之后执行任务二,任务三和任务一任务二一起执行,所有任务都有返回值,等任务二和任务三都执行完成后,在执行任务四
*/
public class CompletableFutureDemo {
public static void main(String[] args) {
CompletableFuture<String> task1 = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
return "任务一已经执行完毕";
});
CompletableFuture<String> task2 = task1.handle((res1,Throwable)->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
return "任务二已经执行完毕";
});
CompletableFuture<String> task3 = CompletableFuture.supplyAsync(()->{
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
return "任务三已经执行完毕";
});
//执行第四步
CompletableFuture<String> task4 = CompletableFuture.allOf(task2,task3).handle((res2,Throwable)->{
try {
return "返回结果4" +task2.get() + task3.get();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
});
String s = task4.join();
System.out.println(s);
}
}