題目
思路
這道題總共有2種思路
方法一
方法二
有更好的方式歡迎大家在下方留言
放一下方法一的代碼,方便大家驗證
<code>public class Solution {
private static final Object lock = new Object();
private static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
char[] result = new char[52];
long totalStart = System.currentTimeMillis();
Thread thread1 = new Thread(() -> {
long thread1Start = System.currentTimeMillis();
for (int i = 0; i < 26; i++) {
synchronized (lock) {
if (flag) {
result[i * 2] = (char)('a' + i);
flag = false;
lock.notify();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
long thread1Cost = System.currentTimeMillis() - thread1Start;
System.out.println("thread1Cost " + thread1Cost);
});
Thread thread2 = new Thread(() -> {
long thread2Start = System.currentTimeMillis();
for (int i = 0; i < 26; i++) {
synchronized (lock) {
if (!flag) {
result[i * 2 + 1] = (char)('A' + i);
flag = true;
lock.notify();
} else {
if (i != 25) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
long thread2Cost = System.currentTimeMillis() - thread2Start;
System.out.println("thread2Cost " + thread2Cost);
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
// aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ
System.out.println(result);
long totalCost = System.currentTimeMillis() - totalStart;
// totalCost 119
System.out.println("totalCost " + totalCost);
}
}/<code>
閱讀更多 Java識堂 的文章