如何创建线程 java
创建线程的两种主要方法
在Java中,可以通过继承Thread类或实现Runnable接口来创建线程。以下是两种方法的详细说明和示例代码。
继承Thread类
通过继承Thread类并重写run()方法,可以创建线程。线程启动时会执行run()方法中的逻辑。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running by extending Thread class");
}
}
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("Thread is running by implementing Runnable interface");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Lambda表达式简化Runnable实现
从Java 8开始,可以使用Lambda表达式简化Runnable接口的实现,避免显式创建类。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread is running using Lambda expression");
});
thread.start();
}
}
线程的常用方法
以下是一些线程常用的方法:
start():启动线程,使其进入可运行状态。run():定义线程执行的任务。sleep(long millis):使线程暂停指定的毫秒数。join():等待线程终止。interrupt():中断线程。
线程的生命周期
线程的生命周期包括以下状态:
- 新建(New):线程对象创建后但未调用
start()方法。 - 可运行(Runnable):调用
start()方法后,线程等待CPU时间片。 - 运行(Running):线程获得CPU时间片并执行
run()方法。 - 阻塞(Blocked):线程等待某个资源或事件(如I/O操作)。
- 终止(Terminated):线程执行完毕或异常退出。
线程同步
多线程环境下,共享资源可能导致数据不一致问题。可以使用synchronized关键字或Lock接口实现线程同步。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.getCount());
}
}
线程池的使用
使用线程池可以高效管理线程资源。Java提供了ExecutorService框架来创建和管理线程池。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
System.out.println("Thread " + Thread.currentThread().getName() + " is running");
});
}
executor.shutdown();
}
}
注意事项
- 避免直接调用
run()方法,否则线程不会异步执行。 - 避免过度使用线程同步,可能导致性能下降。
- 使用线程池时注意资源管理,避免线程泄漏。






