java多线程如何实现
多线程的基本实现方式
Java中实现多线程主要有两种方式:继承Thread类或实现Runnable接口。通过重写run()方法定义线程任务。
继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running");
}
}
// 启动线程
new MyThread().start();
实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
// 启动线程
new Thread(new MyRunnable()).start();
使用线程池管理线程
Java 5+推荐通过ExecutorService线程池管理线程,避免频繁创建销毁线程的开销。

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown();
线程同步与锁机制
多线程共享资源时需使用同步机制防止数据竞争。
synchronized关键字
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
ReentrantLock显式锁

Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程间通信
通过wait()/notify()实现线程协作,或使用BlockingQueue等并发容器。
class SharedResource {
private boolean ready = false;
public synchronized void waitForReady() throws InterruptedException {
while (!ready) wait();
}
public synchronized void setReady() {
ready = true;
notifyAll();
}
}
现代并发工具类
Java并发包提供更高级的同步工具:
CountDownLatch:等待多个线程完成CyclicBarrier:线程到达屏障点后同步Semaphore:控制资源访问并发数CompletableFuture:异步编程组合操作
CompletableFuture.supplyAsync(() -> "Hello")
.thenApplyAsync(s -> s + " World")
.thenAccept(System.out::println);
线程安全集合类
优先使用ConcurrentHashMap、CopyOnWriteArrayList等线程安全集合替代手动同步。
ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
最佳实践建议
- 避免直接操作
Thread类,优先使用线程池 - 减少同步块范围,使用不可变对象
- 使用
ThreadLocal处理线程私有数据 - 注意处理线程中断和异常
- 考虑使用并行流(
parallelStream)简化计算密集型任务






