运用多线程写一个Java案例
时间: 2023-07-01 20:15:19 浏览: 108
下面是一个简单的Java多线程案例,使用了两个线程,一个主线程和一个子线程。主线程和子线程交替输出数字,直到达到指定的数字上限。
```java
public class MultiThreadExample {
private static final int MAX_NUM = 10;
public static void main(String[] args) {
Thread t = new Thread(new PrintThread());
t.start();
for (int i = 1; i <= MAX_NUM; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
static class PrintThread implements Runnable {
public void run() {
for (int i = 1; i <= MAX_NUM; i++) {
System.out.println("Print Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
```
在这个案例中,我们创建了一个PrintThread类实现了Runnable接口,重写了run方法。在主线程中,我们创建了一个PrintThread实例,并使用start方法启动子线程。在主线程中,我们使用for循环输出数字,并使用Thread.sleep方法暂停1秒。在子线程中,我们同样使用for循环输出数字,并使用Thread.sleep方法暂停1秒。执行结果如下:
```
Main Thread: 1
Print Thread: 1
Print Thread: 2
Main Thread: 2
Print Thread: 3
Main Thread: 3
Print Thread: 4
Main Thread: 4
Print Thread: 5
Main Thread: 5
Print Thread: 6
Main Thread: 6
Print Thread: 7
Main Thread: 7
Print Thread: 8
Main Thread: 8
Print Thread: 9
Main Thread: 9
Print Thread: 10
Main Thread: 10
```
阅读全文