多线程输出奇数Java
时间: 2024-02-23 14:29:14 浏览: 73
以下是一个Java多线程程序,用于输出奇数:
```
public class OddNumberPrinter implements Runnable {
private int maxNumber;
public OddNumberPrinter(int maxNumber) {
this.maxNumber = maxNumber;
}
@Override
public void run() {
for (int i = 1; i <= maxNumber; i += 2) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
public static void main(String[] args) {
OddNumberPrinter oddNumberPrinter = new OddNumberPrinter(10);
Thread thread1 = new Thread(oddNumberPrinter, "Thread 1");
Thread thread2 = new Thread(oddNumberPrinter, "Thread 2");
thread1.start();
thread2.start();
}
}
```
在这个程序中,我们创建了一个名为OddNumberPrinter的类,实现了Runnable接口。在run()方法中,我们使用for循环打印从1到maxNumber的所有奇数。在main()方法中,我们创建了两个线程并启动它们。两个线程将会同时运行,并输出1到10之间的所有奇数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)