java如何开线程
Java 线程创建方法
继承 Thread 类
通过继承 Thread 类并重写 run() 方法实现线程逻辑。创建子类实例后调用 start() 方法启动线程。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running by extending Thread");
}
}
// 使用方式
MyThread thread = new MyThread();
thread.start();
实现 Runnable 接口
实现 Runnable 接口的 run() 方法,将实例作为参数传递给 Thread 构造函数。调用 Thread 实例的 start() 方法启动线程。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable");
}
}
// 使用方式
Thread thread = new Thread(new MyRunnable());
thread.start();
使用 Lambda 表达式(Java 8+)
通过 Lambda 表达式简化 Runnable 接口的实现,直接作为参数传递给 Thread 构造函数。
Thread thread = new Thread(() -> {
System.out.println("Thread running via Lambda");
});
thread.start();
实现 Callable 接口(带返回值)
实现 Callable 接口的 call() 方法,通过 FutureTask 包装后传递给 Thread 构造函数。可获取线程执行结果。
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Result from Callable";
}
}
// 使用方式
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
String result = futureTask.get(); // 阻塞获取结果
线程池管理(推荐)
使用 ExecutorService 创建线程池,提交 Runnable 或 Callable 任务,由线程池统一管理线程资源。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> {
System.out.println("Task executed by thread pool");
});
executor.shutdown(); // 关闭线程池
注意事项
- 直接调用
run()方法不会启动新线程,仅在当前线程同步执行。 - 避免频繁创建销毁线程,推荐使用线程池。
- 线程间共享资源需考虑同步问题(如
synchronized或Lock)。 - 继承
Thread类会因单继承限制降低灵活性,通常更推荐实现Runnable或Callable。







