简单写一个java多线程案例
时间: 2023-05-22 11:06:36 浏览: 149
以下是一个简单的Java多线程案例:
```java
public class MultiThreadExample {
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread 1");
MyThread t2 = new MyThread("Thread 2");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
此程序将创建两个线程,分别为 `Thread 1` 和 `Thread 2`,并将它们启动。每个线程将输出 `is running...` 5 次,并在每次输出之间等待 1 秒钟。在此过程中,两个线程将会交替输出。
阅读全文