两个线程轮流打印数字,一直到100java
时间: 2024-02-25 22:10:26 浏览: 54
好的,这里是一个Java代码实现:
```java
public class ThreadExample {
private static int count = 1;
private static Object lock = new Object();
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if (count % 2 == 0) {
System.out.println("Thread 1: " + count);
count++;
}
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (count < 100) {
synchronized (lock) {
if (count % 2 != 0) {
System.out.println("Thread 2: " + count);
count++;
}
}
}
}
});
thread1.start();
thread2.start();
}
}
```
这个程序定义了一个`ThreadExample`类,其中包含了一个静态变量`count`和一个静态对象`lock`。该程序创建了两个线程,每个线程轮流打印数字,直到`count`大于等于100。在每个线程中,我们使用`synchronized`关键字来确保在打印数字时只有一个线程能够访问`count`变量。其中一个线程只打印奇数,而另一个线程只打印偶数。在打印数字后,线程将`count`递增1,以准备下一个数字。