在 Ubuntu 上进行 Java 多线程编程的入门与实战教程
一 环境准备
二 三种创建线程的方式
三 完整示例 线程池 Callable Future 与同步
import java.util.concurrent.*;
public class ThreadPoolSum {
// 线程安全计数器
static class Counter {
private final Object lock = new Object();
private int n = 0;
void add(int delta) { synchronized (lock) { n += delta; } }
int get() { synchronized (lock) { return n; } }
}
static class SumTask implements Callable<Long> {
private final long from, to;
SumTask(long from, long to) { this.from = from; this.to = to; }
@Override public Long call() {
long sum = 0;
for (long i = from; i <= to; i++) sum += i;
// 模拟少量 I/O 或计算抖动
try { Thread.sleep(1); } catch (InterruptedException ignored) {}
return sum;
}
}
public static void main(String[] args) throws Exception {
int n = 1_000_000;
int threads = Runtime.getRuntime().availableProcessors(); // 贴近 CPU 核心数
ExecutorService exec = Executors.newFixedThreadPool(threads);
long t0 = System.nanoTime();
Future<Long>[] futures = new Future[threads];
long chunk = n / threads;
for (int i = 0; i < threads; i++) {
long from = i * chunk + 1;
long to = (i == threads - 1) ? n : (i + 1) * chunk;
futures[i] = exec.submit(new SumTask(from, to));
}
long total = 0;
for (Future<Long> f : futures) total += f.get(); // 阻塞等待结果
long t1 = System.nanoTime();
exec.shutdown();
exec.awaitTermination(10, TimeUnit.SECONDS);
System.out.printf("Sum[1..%d] = %d, 耗时 %.3f ms%n", n, total, (t1 - t0) / 1_000_000.0);
}
}
四 线程安全与常见并发工具
五 调试与排错建议