java如何实现多线程
Java 多线程实现方法
Java 提供了多种实现多线程的方式,以下是常见的几种方法:
继承 Thread 类
通过继承 Thread 类并重写 run() 方法来实现多线程:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现 Runnable 接口
通过实现 Runnable 接口并实现 run() 方法:
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable is 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> {
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();
}
}
使用线程池
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("Task executed by " + Thread.currentThread().getName());
});
}
executor.shutdown();
}
}
使用 CompletableFuture
Java 8 引入了 CompletableFuture 用于异步编程:
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
System.out.println("Async task running");
});
future.join();
}
}
线程同步方法
多线程环境下,同步机制是必要的:
synchronized 关键字
使用 synchronized 关键字实现同步:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
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();
}
}
}
volatile 关键字
volatile 确保变量的可见性:
class SharedObject {
private volatile boolean flag = false;
public void setFlag(boolean value) {
flag = value;
}
}
线程间通信
wait() 和 notify()
使用 wait() 和 notify() 进行线程间通信:
class Message {
private String message;
public synchronized void setMessage(String msg) {
message = msg;
notify();
}
public synchronized String getMessage() throws InterruptedException {
while (message == null) {
wait();
}
return message;
}
}
线程安全集合
Java 提供了线程安全的集合类:
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
}
}
这些方法涵盖了 Java 多线程编程的主要方面,可以根据具体需求选择合适的方式实现多线程。







