写一个多线程的demo java代码
时间: 2023-05-23 13:06:02 浏览: 105
狂神说Java-多线程课程全部代码.rar
A:
以下是一个简单的多线程示例Java代码,使用Runnable接口:
```
public class MultiThreadDemo {
public static void main(String[] args) {
Thread t1 = new Thread(new Task("Thread 1"));
Thread t2 = new Thread(new Task("Thread 2"));
Thread t3 = new Thread(new Task("Thread 3"));
t1.start();
t2.start();
t3.start();
}
}
class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name + " is running.");
}
}
```
该示例创建了3个线程t1、t2、t3,每个线程都执行同一个任务(Runnable接口实现的Task类),该任务只是输出线程名称。在启动线程时,使用Thread类的start()方法。在运行程序时,将输出以下内容(线程执行顺序可能有所不同):
```
Thread 1 is running.
Thread 2 is running.
Thread 3 is running.
```
阅读全文