请用Java代码示例通过实现Runnable接口的方式实现多线程,两个线程轮流打印数字,一直到100
时间: 2024-02-25 21:26:22 浏览: 41
```
public class PrintThread implements Runnable {
private int num;
private static Object lock = new Object();
public PrintThread(int num) {
this.num = num;
}
public void run() {
while (num <= 100) {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + ": " + num);
num += 2;
lock.notifyAll();
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
PrintThread printThread = new PrintThread(1);
Thread thread1 = new Thread(printThread, "Thread 1");
Thread thread2 = new Thread(printThread, "Thread 2");
thread1.start();
thread2.start();
}
}
```
这段代码中,我们实现了一个 `PrintThread` 类,实现了 `Runnable` 接口。在 `run()` 方法中,我们使用 `synchronized` 关键字锁住了一个静态对象 `lock`,并且使用 `wait()` 和 `notifyAll()` 方法来实现两个线程轮流打印数字。当一个线程打印完毕后,它会调用 `notifyAll()` 方法通知另一个线程可以继续执行,然后自己调用 `wait()` 方法等待另一个线程的通知。这样,两个线程就可以交替打印数字,直到打印到 100。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)