如何在Java中实现多线程?

在 Java 中实现多线程主要有三种核心方式,结合 Java 版本演进还延伸出基于线程池的实现方式,以下是详细介绍:

1. 继承Thread

通过继承java.lang.Thread类,重写其run()方法定义线程执行逻辑,调用start()方法启动线程(start()会自动调用run())。
示例
java运行
class MyThread extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            try {
                Thread.sleep(100); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        thread1.setName("线程1");
        thread2.setName("线程2");
        thread1.start(); // 启动线程
        thread2.start();
    }
}
 
缺点:Java 单继承限制,继承Thread后无法继承其他类。

2. 实现Runnable接口

实现java.lang.Runnable接口,重写run()方法,将Runnable实例传入Thread对象启动线程。
示例
java运行
class MyRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class RunnableDemo {
    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        Thread thread1 = new Thread(runnable, "线程1");
        Thread thread2 = new Thread(runnable, "线程2");
        thread1.start();
        thread2.start();
    }
}
 
优点:避免单继承限制,多个线程可共享同一个Runnable实例的资源。

3. 实现Callable接口(Java 5+)

Callable接口允许线程执行后返回结果或抛出异常,需配合FutureTask使用。
示例
java运行
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 5; i++) {
            sum += i;
            System.out.println(Thread.currentThread().getName() + ": 计算到" + i);
            Thread.sleep(100);
        }
        return sum;
    }
}

public class CallableDemo {
    public static void main(String[] args) throws Exception {
        MyCallable callable = new MyCallable();
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        Thread thread = new Thread(futureTask, "计算线程");
        thread.start();
        
        // 获取线程执行结果(会阻塞直到结果返回)
        int result = futureTask.get();
        System.out.println("计算结果:" + result);
    }
}
 
特点:支持返回值、异常处理,适合需要获取线程执行结果的场景。

4. 线程池(Java 5+,推荐)

通过java.util.concurrent.ExecutorService线程池管理线程,避免频繁创建销毁线程的开销,是实际开发中最常用的方式。
示例
java运行
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        // 创建固定大小的线程池(2个线程)
        ExecutorService executor = Executors.newFixedThreadPool(2);
        
        // 提交任务
        executor.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        
        executor.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    System.out.println(Thread.currentThread().getName() + ": " + i);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        
        executor.shutdown(); // 关闭线程池
    }
}
 
常用线程池类型
  • newFixedThreadPool(int n):固定大小线程池;
  • newCachedThreadPool():可缓存线程池(按需创建线程);
  • newSingleThreadExecutor():单线程池;
  • newScheduledThreadPool(int n):定时任务线程池。

核心注意点

  • 启动线程必须调用start()方法,直接调用run()只是普通方法调用,不会创建新线程;
  • 多线程共享资源时需注意线程安全(如使用synchronizedLock等);
  • 避免线程死锁,合理处理InterruptedException(线程中断异常)。
posted @ 2025-12-03 18:30  小java  阅读(1)  评论(0)    收藏  举报