java多线程编程案例
时间: 2023-12-16 11:04:17 浏览: 108
当然,我可以分享一个简单的Java多线程编程案例。以下是一个示例代码,展示了如何使用多个线程同时打印数字:
```java
public class MultiThreadExample {
public static void main(String[] args) {
// 创建并启动三个线程
Thread thread1 = new NumberThread(1, 10);
thread1.start();
Thread thread2 = new NumberThread(11, 20);
thread2.start();
Thread thread3 = new NumberThread(21, 30);
thread3.start();
}
}
class NumberThread extends Thread {
private int start;
private int end;
public NumberThread(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
System.out.println(i);
}
}
}
```
在这个例子中,我们创建了一个继承自Thread类的NumberThread类。在NumberThread类的run()方法中,我们使用一个for循环来打印指定范围内的数字。然后,在主线程中创建并启动了三个NumberThread对象,每个线程负责打印一部分数字。
当我们运行这个程序时,会看到三个线程同时运行,并且按照各自的范围打印数字。这就是一个简单的Java多线程编程案例。
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![gz](https://img-home.csdnimg.cn/images/20210720083447.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![text/plain; charset=iso-8859-1](https://img-home.csdnimg.cn/images/20250102104920.png)