Java如何创建多线程
创建多线程的几种方法
Java中创建多线程主要有以下三种方式:继承Thread类、实现Runnable接口、实现Callable接口并结合ExecutorService使用。
继承Thread类
通过继承Thread类并重写run()方法可以创建线程。这种方式简单直接,但Java不支持多重继承,因此如果类已经继承了其他类,就无法使用这种方法。
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接口是更灵活的方式,因为Java支持多重接口实现。需要实现run()方法,并将Runnable实例传递给Thread类的构造函数。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable interface");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
实现Callable接口
Callable接口允许线程返回结果或抛出异常,通常与ExecutorService一起使用。Callable的call()方法可以返回泛型类型的结果。
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Thread running by implementing Callable interface";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get());
executor.shutdown();
}
}
线程池的使用
Java提供了ExecutorService和Executors类来管理线程池,避免频繁创建和销毁线程的开销。
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++) {
Runnable worker = new WorkerThread("Task " + i);
executor.execute(worker);
}
executor.shutdown();
}
}
class WorkerThread implements Runnable {
private String taskName;
public WorkerThread(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " executing " + taskName);
}
}
线程同步
多线程环境下共享资源可能导致数据不一致,可以使用synchronized关键字或Lock接口实现线程同步。
使用synchronized方法
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("Count: " + counter.getCount());
}
}
使用Lock接口
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
return count;
}
}
线程间通信
wait()、notify()和notifyAll()方法用于线程间通信,必须在同步块或同步方法中调用。
class SharedResource {
private boolean flag = false;
public synchronized void produce() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
flag = true;
System.out.println("Produced");
notify();
}
public synchronized void consume() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
flag = false;
System.out.println("Consumed");
notify();
}
}
public class Main {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread producer = new Thread(resource::produce);
Thread consumer = new Thread(resource::consume);
producer.start();
consumer.start();
}
}






