编写两个线程类,分别命名为First和Second,可选用继承Thread类或者执行Runnable接口的方法创建这两个线程类,线程可循环3次输出自己线程的名字;
时间: 2024-03-01 10:49:54 浏览: 65
好的,以下是使用继承Thread类的方法创建两个线程类First和Second:
```java
public class First extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
public class Second extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
```
以下是使用执行Runnable接口的方法创建两个线程类First和Second:
```java
public class First implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
public class Second implements Runnable {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println("Thread name: " + Thread.currentThread().getName());
}
}
}
```
在主函数中,我们可以创建两个线程对象并调用start()方法启动线程:
```java
public static void main(String[] args) {
Thread t1 = new First();
Thread t2 = new Second();
t1.start();
t2.start();
}
```
运行程序后,会输出以下结果:
```
Thread name: Thread-0
Thread name: Thread-0
Thread name: Thread-0
Thread name: Thread-1
Thread name: Thread-1
Thread name: Thread-1
```
阅读全文