上代碼:
import java.util.ArrayList;
import java.util.List;
public class ThreadSortsPrint {
private static volatile char c = 'C';
private static List<Character> list = new ArrayList<>(1000);
public static void main(String[] args) throws InterruptedException {
System.out.println(Math.round(-1.5));
Thread t1 = new Thread(() -> {
int count = 0;
while (count <100) {
synchronized (ThreadSortsPrint.class) {
if (c =='C') {
System.out.print("A");
c = 'A';
list.add(c);
count++;
ThreadSortsPrint.class.notifyAll();
}else {
try {
ThreadSortsPrint.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t2 = new Thread(() -> {
int count = 0;
while (count <100) {
synchronized (ThreadSortsPrint.class) {
if (c == 'A') {
System.out.print("B");
c = 'B';
list.add(c);
count++;
ThreadSortsPrint.class.notifyAll();
}else {
try {
ThreadSortsPrint.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
Thread t3 = new Thread(() -> {
int count = 0;
while (count <100) {
synchronized (ThreadSortsPrint.class) {
if (c =='B') {
System.out.print("C");
c = 'C';
list.add(c);
count++;
ThreadSortsPrint.class.notifyAll();
}else {
try {
ThreadSortsPrint.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});
t1.start();
t2.start();
t3.start();
t1.join();
t2.join();
t3.join();
StringBuilder stringBuilder = new StringBuilder();
for(Character c:list){
System.out.print(c);
stringBuilder.append(c);
}
System.out.println();
System.out.println(stringBuilder.length());
}
}
輸出結果: