java线程如何启动
启动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接口的实现,直接传递给Thread构造函数。
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(5);
executor.execute(() -> {
System.out.println("Thread pool thread is running");
});
executor.shutdown();
}
}
注意事项
- 直接调用
run()方法不会启动新线程,仅作为普通方法执行。 start()方法会触发JVM创建新线程并调用run()。- 避免多次调用
start(),否则会抛出IllegalThreadStateException。







