编写一个程序,开启 3 个线程 A,B,C,这三个线程的输出分别为 A、B、C,每个线程将自己的 输出在屏幕上打印 100 遍,要求输出的结果必须按顺序显示。如:ABCABCABC....
public class PrintABC {
private static String message = "A";
public static void main(String[] args) {
Thread A = new Thread(() -> {
int count = 1;
while (count < 101) {
while (!message.equals("A")) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(count);
System.out.println(message);
message = "B";
count = count + 1;
}
});
Thread B = new Thread(() -> {
int count = 1;
while (count < 101) {
while (!message.equals("B")) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(count);
System.out.println(message);
message = "C";
count = count + 1;
}
});
Thread C = new Thread(() -> {
int count = 1;
while (count < 101) {
while (!message.equals("C")) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(count);
System.out.println(message);
message = "A";
count = count + 1;
}
});
A.start();
B.start();
C.start();
}
}
public class PrintABC2notifyAll {
private volatile static String message = "A";
static Object lock = new Object();
public static void main(String[] args) {
Thread A = new Thread(() -> {
int count = 1;
synchronized (lock) {
while (count < 101) {
while (!message.equals("A")) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(count + message);
message = "B";
count = count + 1;
lock.notifyAll();
}
}
});
Thread B = new Thread(() -> {
int count = 1;
synchronized (lock) {
while (count < 101) {
while (!message.equals("B")) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(count + message);
message = "C";
count = count + 1;
lock.notifyAll();
}
}
});
Thread C = new Thread(() -> {
int count = 1;
synchronized (lock) {
while (count < 101) {
while (!message.equals("C")) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(count + message);
message = "A";
count = count + 1;
lock.notifyAll();
}
}
});
A.start();
B.start();
C.start();
}
}