java线程如何启动
启动Java线程的方法
在Java中,线程可以通过继承Thread类或实现Runnable接口来启动。以下是两种主要方法的详细说明:
继承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()方法,可以创建线程任务。然后将Runnable实例传递给Thread类的构造函数来启动线程。

class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread 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("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("Thread is running.");
});
executor.shutdown();
}
}
注意事项
- 调用
start()方法会启动新线程并执行run()方法,直接调用run()方法不会启动新线程。 - 线程启动后无法再次调用
start()方法,否则会抛出IllegalThreadStateException异常。 - 线程的执行顺序由线程调度器决定,无法保证顺序。






