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类的实例。这种方式更灵活,适合多线程共享资源。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable 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("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.submit(() -> {
System.out.println("Thread pool thread is running");
});
executor.shutdown();
}
}
注意事项
- 直接调用
run()方法不会启动新线程,仅作为普通方法执行。 - 线程启动后由JVM调度,执行顺序不确定。
- 避免频繁创建和销毁线程,推荐使用线程池。







