如何实现java多线程
实现Java多线程的方法
Java多线程的实现主要通过继承Thread类或实现Runnable接口完成,也可以使用ExecutorService等高级工具类。
继承Thread类
通过继承Thread类并重写run()方法实现多线程:
class MyThread extends Thread {
@Override
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接口并传递给Thread类的构造函数:
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Callable和Future
Callable接口允许线程返回结果,配合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创建线程池管理线程:
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 " + Thread.currentThread().getId() + " running");
});
}
executor.shutdown();
}
}
同步与锁机制
使用synchronized关键字或Lock接口实现线程同步:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return 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());
}
}
使用CompletableFuture
Java 8引入的CompletableFuture支持异步编程:
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Async result";
});
System.out.println(future.get());
}
}
线程安全注意事项
- 避免竞态条件,使用同步机制保护共享资源
- 注意死锁问题,避免多个线程互相等待
- 考虑使用
volatile关键字保证变量可见性 - 优先使用线程安全的集合类如
ConcurrentHashMap
线程生命周期管理
- 使用
interrupt()方法中断线程 - 通过
join()方法等待线程完成 - 合理设置线程优先级
- 注意处理未捕获异常







