java三个线程交替打印1-100
时间: 2024-12-09 12:17:13 浏览: 10
在Java中,我们可以使用`Thread.sleep()`方法以及`synchronized`关键字来创建并控制三个线程交替打印数字1到100。下面是一个简单的示例:
```java
public class PrintNumber {
private int count = 1;
private final Object lock = new Object();
public class Worker implements Runnable {
@Override
public void run() {
for (int i = 0; i < 34; i++) { // 每个线程打印34次,保证1-100
synchronized (lock) {
if (count > 100) {
break;
}
System.out.println(Thread.currentThread().getName() + ": " + count++);
try {
lock.notify(); // 醒来下一个线程
lock.wait(50); // 等待50毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
PrintNumber printNum = new PrintNumber();
Thread t1 = new Thread(printNum.new Worker(), "Thread 1");
Thread t2 = new Thread(printNum.new Worker(), "Thread 2");
Thread t3 = new Thread(printNum.new Worker(), "Thread 3");
t1.start();
t2.start();
t3.start();
阅读全文