java多线程如何实现
实现多线程的三种核心方法
Java多线程的实现主要通过以下三种方式:继承Thread类、实现Runnable接口、使用Callable和Future结合线程池。
继承Thread类
通过继承Thread类并重写run()方法,创建线程实例后调用start()方法启动线程。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running by extending Thread class");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
实现Runnable接口
实现Runnable接口的run()方法,将实例传递给Thread类的构造函数。这种方式更灵活,适合多线程共享资源。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Callable和Future
Callable接口允许线程返回结果或抛出异常,通常配合ExecutorService和Future使用。
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Callable task result";
}
}
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();
}
}
线程池管理
使用ExecutorService线程池管理多线程任务,避免频繁创建销毁线程的开销。
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.execute(() -> {
System.out.println("Thread running in pool: " + Thread.currentThread().getName());
});
}
executor.shutdown();
线程同步与锁
多线程共享资源时需使用同步机制,如synchronized关键字或ReentrantLock。
class Counter {
private int count = 0;
private final Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程间通信
通过wait()、notify()或Condition实现线程间协调。

class SharedResource {
private boolean flag = false;
public synchronized void waitForFlag() throws InterruptedException {
while (!flag) {
wait();
}
}
public synchronized void setFlag() {
flag = true;
notifyAll();
}
}
以上方法覆盖了Java多线程的核心实现方式,可根据具体场景选择合适方案。






