今天筆者收到老師的一個題目,讓我準備兩個流程,依次實作輸出以下資訊
如:
執行緒A 列印 字母a ,執行緒B 列印數字1
執行緒A 列印 字母b ,執行緒B 列印數字2
執行緒A 列印 字母c ,執行緒B 列印數字3
執行緒A 列印 字母d ,執行緒B 列印數字4
,,,
依次列印完畢26個字母和26個數字
,輸出效果為:
a1b2c3...z26
下文筆者就將具體的實作思路展示如下:
1.將借助多執行緒的wait方法
2.借助一個外部變數
package com.java265.other;
public class Test6 {
/*
* 兩個執行緒 一個執行緒輸出 a b c d e f 一個執行緒輸出 1 2 3 4 5 交叉輸出 a 1 b 2 c 3
*/
static boolean flag = false;
public static void main(String[] args) {
Object o = new Object();
Thread t1, t2;
t1 = new Thread(() -> {
for (int i = 0; i < 26; ) {
synchronized (o) {
if (!flag) {
char t = (char) (i + (int) 'a');
System.out.print(t);
i++;
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
flag = false;
o.notifyAll();
}
}
}
});
t2 = new Thread(() -> {
for (int i = 1; i <= 26;) {
synchronized (o) {
if (flag) {
System.out.print(i);
i++;
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag = true;
o.notifyAll();
}
}
});
t1.start();
t2.start();
}
}
參照資料:
http://java265.com/JavaMianJing/202112/16383980681974.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511023.html
標籤:其他
