分别使用继承 Thread 类的方式和实现 Runnable 接口的方式创建主线程 main 和子线程,修改两个线程的名称分别为李雷和韩梅梅,让其同步循环打印出“李雷线程输出:i”和“韩梅梅线程输出:i”。循环次数为 30 次。
时间: 2024-10-23 19:04:37 浏览: 20
在Java中,有两种常见的方式创建线程:通过继承`Thread`类和实现`Runnable`接口。这里我会分别演示这两种方法,并设置线程名称。
**1. 继承Thread类的方式:**
```java
class LiLeiThread extends Thread {
private String name = "李雷";
public LiLeiThread() {
super();
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(name + "线程输出:" + i);
}
}
}
public class HanMeimeiThread extends Thread {
private String name = "韩梅梅";
public HanMeimeiThread() {
super();
}
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(name + "线程输出:" + i);
}
}
}
public class Main {
public static void main(String[] args) {
LiLeiThread lilei = new LiLeiThread();
HanMeimeiThread hanmeimei = new HanMeimeiThread();
lilei.setName("李雷");
hanmeimei.setName("韩梅梅");
lilei.start(); // 启动李雷线程
hanmeimei.start(); // 启动韩梅梅线程
}
}
```
**2. 实现Runnable接口的方式:**
```java
class LiLeiRunnable implements Runnable {
private String name = "李雷";
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(name + "线程输出:" + i);
}
}
}
class HanMeimeiRunnable implements Runnable {
private String name = "韩梅梅";
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println(name + "线程输出:" + i);
}
}
}
public class Main {
public static void main(String[] args) {
Thread lileiThread = new Thread(new LiLeiRunnable());
Thread hanmeimeiThread = new Thread(new HanMeimeiRunnable());
lileiThread.setName("李雷");
hanmeimeiThread.setName("韩梅梅");
lileiThread.start(); // 启动李雷线程
hanmeimeiThread.start(); // 启动韩梅梅线程
}
}
```
阅读全文