Java 创建线程的方式
Java 提供了多种创建线程的方式。理解不同的创建方式及其适用场景是掌握多线程编程的基础。本章将详细介绍 Java 中创建线程的各种方法。
继承 Thread 类
基本方式
继承 Thread 类并重写 run() 方法:
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
// 使用
MyThread thread = new MyThread();
thread.start(); // 启动线程
完整示例
public class ThreadExtendExample extends Thread {
private String threadName;
public ThreadExtendExample(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " 执行:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadExtendExample thread1 = new ThreadExtendExample("线程1");
ThreadExtendExample thread2 = new ThreadExtendExample("线程2");
thread1.start();
thread2.start();
}
}
优缺点
优点:
- 简单直接
- 可以直接使用 Thread 类的方法
缺点:
- Java 单继承,不能继承其他类
- 不符合面向对象设计原则(继承应该表示"是一个"关系)
实现 Runnable 接口
基本方式
实现 Runnable 接口并实现 run() 方法:
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
// 使用
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
完整示例
public class RunnableExample implements Runnable {
private String taskName;
public RunnableExample(String taskName) {
this.taskName = taskName;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(taskName + " 执行:" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Runnable task1 = new RunnableExample("任务1");
Runnable task2 = new RunnableExample("任务2");
Thread thread1 = new Thread(task1);
Thread thread2 = new Thread(task2);
thread1.start();
thread2.start();
}
}