java如何实现多线程
Java 多线程实现方法
Java 提供了多种实现多线程的方式,以下是常见的几种方法:
继承 Thread 类
通过继承 Thread 类并重写 run() 方法实现多线程。创建子类实例后调用 start() 方法启动线程。
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现 Runnable 接口
实现 Runnable 接口并重写 run() 方法,将实现类实例作为参数传递给 Thread 类构造函数。
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
实现 Callable 接口
Callable 接口允许线程返回结果或抛出异常,通常与 ExecutorService 结合使用。
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
public String call() throws Exception {
return "Thread completed";
}
}
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get());
executor.shutdown();
}
}
使用线程池
Java 提供了 ExecutorService 框架来管理线程池,避免频繁创建和销毁线程的开销。

import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println("Thread running");
});
}
executor.shutdown();
}
}
Lambda 表达式简化
Java 8 引入的 Lambda 表达式可以简化 Runnable 接口的实现。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread running");
});
thread.start();
}
}
线程同步与通信
使用 synchronized 关键字
synchronized 关键字用于实现线程同步,确保同一时间只有一个线程访问共享资源。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
使用 Lock 接口
Lock 接口提供了更灵活的锁机制,例如 ReentrantLock。

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private final Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
使用 wait() 和 notify()
wait() 和 notify() 方法用于线程间通信,实现线程的等待和唤醒机制。
class SharedResource {
private boolean ready = false;
public synchronized void waitForReady() throws InterruptedException {
while (!ready) {
wait();
}
}
public synchronized void setReady() {
ready = true;
notifyAll();
}
}
线程安全集合类
Java 提供了多种线程安全的集合类,如 ConcurrentHashMap、CopyOnWriteArrayList 等。
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
}
}
线程异常处理
线程中的异常需要通过 UncaughtExceptionHandler 处理。
Thread thread = new Thread(() -> {
throw new RuntimeException("Exception in thread");
});
thread.setUncaughtExceptionHandler((t, e) -> {
System.out.println("Exception caught: " + e.getMessage());
});
thread.start();
以上方法涵盖了 Java 多线程的主要实现方式,开发者可以根据具体需求选择合适的方法。






