java3、用多线程模拟实现以下操作: 左手画一个圈 左手画二个圈 左手画三个圈 右手画一个圈 右手画二个圈 右手画三个圈
时间: 2023-09-08 07:10:55 浏览: 37
可以使用Java的多线程来模拟实现上述操作。以下是一个可能的实现示例:
```java
class DrawingThread extends Thread {
private String hand;
private int numCircles;
public DrawingThread(String hand, int numCircles) {
this.hand = hand;
this.numCircles = numCircles;
}
@Override
public void run() {
for (int i = 1; i <= numCircles; i++) {
System.out.println(hand + "手画" + i + "个圈");
}
}
}
public class Main {
public static void main(String[] args) {
// 创建两个线程分别表示左手和右手
Thread leftHandThread = new DrawingThread("左", 3);
Thread rightHandThread = new DrawingThread("右", 3);
// 启动线程
leftHandThread.start();
rightHandThread.start();
// 等待线程执行完毕
try {
leftHandThread.join();
rightHandThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
```
运行上述代码,会输出以下结果:
```
左手画1个圈
左手画2个圈
左手画3个圈
右手画1个圈
右手画2个圈
右手画3个圈
```
上述代码中,创建了一个`DrawingThread`类,继承自`Thread`类。`DrawingThread`类表示一个画圈的线程,通过构造方法传入手的信息(左手或右手)以及要画的圈的数量。在`run`方法中,使用循环逐个输出画圈的操作。在`Main`类中,创建左手和右手的线程并启动,然后使用`join`方法等待线程执行完毕。这样就能够模拟多线程画圈的操作了。