java 如何启动线程
启动线程的方法
在Java中,启动线程主要有两种方式:通过继承Thread类或实现Runnable接口。以下是具体实现方法:
继承Thread类
创建一个类继承Thread类并重写run方法,然后实例化并调用start方法启动线程。
class MyThread extends Thread {
@Override
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方法,然后将该实例传递给Thread构造函数并调用start方法。
class MyRunnable implements Runnable {
@Override
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();
}
}
使用Lambda表达式(Java 8+)
对于简单的任务,可以直接使用Lambda表达式实现Runnable接口。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Lambda thread is running");
});
thread.start();
}
}
通过线程池启动
使用ExecutorService可以更高效地管理线程资源。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(() -> System.out.println("Task executed by thread pool"));
executor.shutdown();
}
}
注意事项
- 调用
start方法会启动新线程并执行run方法,直接调用run方法会在当前线程中执行。 - 避免多次调用
start方法,否则会抛出IllegalThreadStateException。 - 推荐使用
Runnable接口或线程池,避免单继承的限制和资源浪费。






