java如何创建线程
创建线程的方法
在Java中,创建线程主要有两种方式:继承Thread类和实现Runnable接口。以下是具体的实现方法。
继承Thread类
通过继承Thread类并重写run()方法,可以创建一个线程。以下是示例代码:

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 is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Lambda表达式(Java 8及以上)
对于简单的线程任务,可以使用Lambda表达式简化代码:

public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Lambda thread is running");
});
thread.start();
}
}
使用Callable和Future(带返回值)
如果需要线程返回结果,可以使用Callable和Future:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Callable result";
}
}
public class Main {
public static void main(String[] args) throws Exception {
FutureTask<String> task = new FutureTask<>(new MyCallable());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
}
}
使用线程池
对于需要管理多个线程的场景,可以使用线程池:
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 in pool is running");
});
executor.shutdown();
}
}
注意事项
- 直接调用
run()方法不会启动新线程,而是会在当前线程中执行。 - 线程的启动顺序并不一定代表执行顺序,具体由操作系统调度决定。
- 避免直接继承
Thread类,推荐实现Runnable接口,因为Java不支持多重继承。






