Java多線程應(yīng)用循環(huán)輸出ABC方式
Java 多線程應(yīng)用循環(huán)輸出ABC
有三個線程ID分別是A、B、C,請用多線編程實現(xiàn),在屏幕上循環(huán)打印10次ABCABC
請補充以下代碼
public class Test {
public static void main(String[] args) {
MajusculeABC maj = new MajusculeABC();
Thread t_a = new Thread(new Thread_ABC(maj , 'A'));
Thread t_b = new Thread(new Thread_ABC(maj , 'B'));
Thread t_c = new Thread(new Thread_ABC(maj , 'C'));
t_a.start();
t_b.start();
t_c.start();
}
}
class MajusculeABC {
請補充代碼
}
class Thread_ABC implements Runnable {
請補充代碼
}答案如下
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
MajusculeABC maj = new MajusculeABC();
Thread t_a = new Thread(new Thread_ABC(maj , 'A'));
Thread t_b = new Thread(new Thread_ABC(maj , 'B'));
Thread t_c = new Thread(new Thread_ABC(maj , 'C'));
t_a.start();
t_b.start();
t_c.start();
}
private static class MajusculeABC {
// 請補充代碼
public MajusculeABC() {
}
private int a = 1;
private synchronized void print(int index, char s) throws InterruptedException {
do {
if (s == 'A' && a == 1) {
a++;
System.out.println(index+"---" + s);
notifyAll();
break;
} else if (s == 'B' && a == 2) {
a++;
System.out.println(index+"---" + s);
notifyAll();
break;
} else if (s == 'C' && a == 3) {
a = 1;
System.out.println(index+"---" + s);
notifyAll();
break;
} else {
wait();
}
} while (true);
}
}
private static class Thread_ABC implements Runnable {
private char s;
private MajusculeABC majusculeABC;
// 請補充代碼
public Thread_ABC(MajusculeABC majusculeABC, char s) {
this.majusculeABC = majusculeABC;
this.s = s;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
majusculeABC.print(i, s);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}輸出如下:
0---A
0---B
0---C
1---A
1---B
1---C
2---A
2---B
2---C
3---A
3---B
3---C
4---A
4---B
4---C
5---A
5---B
5---C
6---A
6---B
6---C
7---A
7---B
7---C
8---A
8---B
8---C
9---A
9---B
9---C
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring-boot通過@Scheduled配置定時任務(wù)及定時任務(wù)@Scheduled注解的方法
這篇文章主要介紹了spring-boot通過@Scheduled配置定時任務(wù),文中還給大家介紹了springboot 定時任務(wù)@Scheduled注解的方法,需要的朋友可以參考下2017-11-11
Java實現(xiàn)多個單張tif文件合并成一個多頁tif文件
業(yè)務(wù)部門需要將多個單張的tiff文件,合并成一個多頁的tiff文件,本文就來介紹一下如何實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2023-09-09
使用Java進行FreeMarker的web模板開發(fā)的基礎(chǔ)教程
這篇文章主要介紹了使用Java進行FreeMarker模板引擎開發(fā)的基礎(chǔ)教程,文中針對FreeMarker的網(wǎng)頁標簽用法給出了一些例子,需要的朋友可以參考下2016-03-03
詳解Spring ApplicationContext加載過程
這篇文章主要介紹了Spring ApplicationContext加載過程的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用spring框架,感興趣的朋友可以了解下2021-03-03

