编写一个程序,启动三个线程,三个线程的名称分别为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());
flag=2;
//存在多个等待线程时需将其全部唤醒,否则会出现死锁情况
notifyAll();
count++;
}
public synchronized void printB(){
while (flag!=2){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2
System.out.print(Thread.currentThread().getName());
flag=3;
notifyAll();
count++;
}
public synchronized void printC(){
while (flag!=3){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//3
System.out.print(Thread.currentThread().getName());
flag=1;
notifyAll();
count++;
}
}
class MyThread implements Runnable{
private Print print;
public MyThread(Print print) {
this.print = print;
}
@Override
public void run() {
//判断A出现
while (print.getCount()<13){
if(Thread.currentThread().getName().equals("A")){
print.printA();
}else if(Thread.currentThread().getName().equals("B")){
print.printB();
}else if(Thread.currentThread().getName().equals("C")){
print.printC();
}
}
}
}
public class Test{
public static void main(String[] args) {
Print print=new Print();
MyThread mt=new MyThread(print);
Thread thread1=new Thread(mt,"A");
Thread thread2=new Thread(mt,"B");
Thread thread3=new Thread(mt,"C");
thread1.start();
thread2.start();
thread3.start();
}
}