编写一个程序,启动三个线程,三个线程的名称分别为A、B、C;每个线程将自己的名称在屏幕上打印5遍,打印顺序是ABCABC…
解题思路:该题为多个线程交替输出,且输出5次;故我们需要启动三个线程,设置标志位(int flag)明确当前线程,利用count计数器控制输出次数;明确某一线程启动时其他线程等待及唤醒操作。
class Print{
private Integer flag=1;
private Integer count=0;
public Integer getCount() {
return count;
}
public synchronized void printA(){
//同时唤醒多个等待线程时,需重新判断标志位的值(因下一次获得锁的线程不明确,有可能是C线程获得锁,此时仍需要等待而非直接打印)
while (flag!=1){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//1
System.out.print(Thread.currentThread().getName());