Java并发工具类详解:从Executors到CompletableFuture
大家好,我是微赚淘客返利系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!
一、Java并发编程基础
Java并发编程是利用多线程来提高程序性能和响应能力的关键技术。Java提供了丰富的并发工具来帮助开发者编写高效的并发程序。
二、Executor框架
Executor框架是Java并发编程的核心,它定义了任务的执行方式。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import cn.juwatech.task.MyRunnable;
public class ExecutorExample {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
executor.submit(new MyRunnable());
}
executor.shutdown();
}
}
三、Executors的几种线程池
Executors提供了几种静态工厂方法来创建不同类型的线程池。
// 创建一个固定大小的线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
// 创建一个单线程的线程池
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
// 创建一个可缓存的线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
四、Callable与Future
Callable任务可以返回结果,并且可以抛出异常。Future用于获取Callable任务的结果。
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import cn.juwatech.task.MyCallable;
public class CallableExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<String> future = executor.submit(new MyCallable());
System.out.println("Result: " + future.get());
executor.shutdown();
}
}
五、同步辅助工具类
CountDownLatch、CyclicBarrier、Semaphore和Exchanger是Java提供的同步辅助工具类。
import java.util.concurrent.CountDownLatch;
public class LatchExample {
public static void main(String[] args) throws InterruptedException {
int threadCount = 5;
CountDownLatch latch = new CountDownLatch(threadCount);
for (int i = 0; i < threadCount; i++) {
new Thread(new LatchTask(latch)).start();
}
latch.await(); // 等待所有线程完成
System.out.println("All tasks completed.");
}
}
class LatchTask implements Runnable {
private final CountDownLatch latch;
public LatchTask(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
// 执行任务
} finally {
latch.countDown();
}
}
}
六、并发集合
Java提供了一些并发集合类,如ConcurrentHashMap、CopyOnWriteArrayList等。
import java.util.concurrent.ConcurrentHashMap;
public class ConcurrentCollectionExample {
public static void main(String[] args) {
ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>();
// 线程安全的Map操作
}
}
七、Fork/Join框架
Fork/Join框架是Java 7中引入的,用于并行处理任务。
import java.util.concurrent.RecursiveTask;
import cn.juwatech.task.MyForkJoinTask;
public class ForkJoinExample {
public static void main(String[] args) {
MyForkJoinTask task = new MyForkJoinTask(0, 1000 * 1000);
task.fork(); // 并行计算
}
}
八、CompletableFuture
CompletableFuture是Java 8中引入的,用于编写异步的非阻塞代码。
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
// 模拟长时间运行的任务
return "Result";
}).thenAccept(result -> {
System.out.println(result);
}).exceptionally(ex -> {
ex.printStackTrace();
return null;
});
}
}
九、CompletableFuture的组合使用
多个CompletableFuture可以组合使用,实现更复杂的异步逻辑。
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
// 异步任务1
});
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
// 异步任务2
return "Data";
});
future2.thenAcceptBoth(future1, (data, ignored) -> {
// 两个任务都完成后的逻辑
});
十、线程工厂
自定义线程工厂可以创建具有特定属性的线程。
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import cn.juwatech.thread.MyThreadFactory;
public class ThreadFactoryExample {
public static void main(String[] args) {
ThreadFactory factory = new MyThreadFactory();
Thread thread = factory.newThread(() -> {
// 线程任务
});
thread.start();
}
}
class MyThreadFactory implements ThreadFactory {
private final AtomicInteger count = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "CustomThread-" + count.getAndIncrement());
}
}
本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!