java代码示例通过实现Runnable接口的方式实现多线程,两个线程轮流打印数字,一直到100
时间: 2024-02-25 17:09:25 浏览: 82
好的,以下是 java 代码示例:
```java
public class MultiThreadExample {
private static final int MAX_NUM = 100;
private static final Object lock = new Object();
private static int num = 1;
public static void main(String[] args) {
Thread t1 = new Thread(new PrintNumTask(1));
Thread t2 = new Thread(new PrintNumTask(2));
t1.start();
t2.start();
}
static class PrintNumTask implements Runnable {
private int id;
public PrintNumTask(int id) {
this.id = id;
}
@Override
public void run() {
while (true) {
synchronized (lock) {
if (num > MAX_NUM) {
break;
}
if (num % 2 == id - 1) {
System.out.println("Thread-" + id + ": " + num);
num++;
}
}
}
}
}
}
```
上述代码中,我们创建了两个实现了 Runnable 接口的任务类 PrintNumTask,并将它们分别传入两个 Thread 对象中启动。在任务类中,我们使用了一个共享的锁 lock,以保证两个任务的操作是互斥的。其中,id 为 1 的任务打印奇数,id 为 2 的任务打印偶数。当 num 大于最大值 MAX_NUM 时,任务退出循环。
输出结果为:
```
Thread-1: 1
Thread-2: 2
Thread-1: 3
Thread-2: 4
Thread-1: 5
Thread-2: 6
Thread-1: 7
Thread-2: 8
Thread-1: 9
Thread-2: 10
...
Thread-1: 99
Thread-2: 100
```
阅读全文