三个线程循环打印abc
时间: 2023-09-06 16:07:21 浏览: 191
为了实现三个线程循环打印ABC,可以使用Synchronized同步方法和Object的wait()和notify()方法。首先,创建三个线程A、B、C,并设置它们的打印次数为10。然后,通过使用三个对象锁a、b、c来控制线程的执行顺序。A线程首先获得c对象锁,打印A后释放c对象锁,并通过notify()方法唤醒B线程。B线程等待a对象锁,获取到a对象锁后打印B,并释放a对象锁,然后通过notify()方法唤醒C线程。C线程等待b对象锁,获取到b对象锁后打印C,并释放b对象锁,并通过notify()方法唤醒A线程。这样就实现了三个线程循环打印ABC的需求。
以下是一个示例代码:
```java
class PrintThread implements Runnable {
private static final Object a = new Object();
private static final Object b = new Object();
private static final Object c = new Object();
private String name;
public PrintThread(String name) {
this.name = name;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (name) {
try {
switch (name) {
case "A":
synchronized (c) {
System.out.print("A");
c.notify();
}
name.wait();
break;
case "B":
synchronized (a) {
System.out.print("B");
a.notify();
}
name.wait();
break;
case "C":
synchronized (b) {
System.out.print("C");
b.notify();
}
name.wait();
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread threadA = new Thread(new PrintThread("A"));
Thread threadB = new Thread(new PrintThread("B"));
Thread threadC = new Thread(new PrintThread("C"));
threadA.start();
threadB.start();
threadC.start();
}
}
```
通过以上代码,三个线程将按照ABCABCABC的顺序循环打印10次。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [多线程交替打印ABC的多种实现方法](https://blog.csdn.net/xiaokang123456kao/article/details/77331878)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [三个线程轮流打印ABC](https://blog.csdn.net/yu1336199790/article/details/118725454)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文
相关推荐














