java中如何实现多线程
继承Thread类
通过继承Thread类并重写run()方法实现多线程。创建子类实例后调用start()方法启动线程。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
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("Runnable running: " + Thread.currentThread().getName());
}
}
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 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)
通过线程池管理多个线程,避免频繁创建销毁线程的开销。常用Executors工具类创建线程池。
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
System.out.println("Pooled thread: " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
Lambda表达式简化
Java 8+可使用Lambda表达式简化Runnable或Callable的实现。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Lambda thread: " + Thread.currentThread().getName());
});
thread.start();
}
}
线程同步
使用synchronized关键字或Lock接口解决多线程共享资源的竞争问题。

class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount());
}
}






