编写一个简单程序,分别用两种线程的创建方式来生成线程。
时间: 2024-12-25 11:32:23 浏览: 3
在Java中,有两种主要的方式来创建线程:继承Thread类和实现Runnable接口。以下是两个示例:
**1. 继承Thread类**
```java
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
}
}
public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1");
MyThread thread2 = new MyThread("Thread 2");
// 启动线程
thread1.start();
thread2.start();
}
}
```
**2. 实现Runnable接口**
```java
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + ": " + i);
}
}
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable("Thread 1"));
Thread thread2 = new Thread(new MyRunnable("Thread 2"));
// 启动线程
thread1.start();
thread2.start();
}
}
```
在这两个例子中,我们创建了两个线程,每个线程都有自己的名字,并打印出从0到4的数字。`start()`方法用于启动线程执行。
阅读全文