【简单多线程问题】3个线程分别打印5次A、B、C,打印顺序为ABC...
我的问题如下:
为什么run()方法中的判断语句是getCount()<13?
从输出结果可以看出,程序最后到了count值为15的时候才结束。但是count值从13开始,run()方法就不会被调用了才对啊。
还是说这样的运行结果和wait()及notifyAll()方法的使用有关,有大神能解释一下吗?
一、测试类:
public class Test {
public static void main(String[] args) {
//创建一个PrintCopy类的对象
PrintCopy pc=new PrintCopy();
//将PrintCopy类的对象作为参数传给一个Print对象
Print print=new Print(pc);
//新建3个线程,并同时取名为"A"、"B"、"C"
Thread t1=new Thread(print,"A");
Thread t2=new Thread(print,"B");
Thread t3=new Thread(print,"C");
//启动线程
t1.start();
t2.start();
t3.start();
}
}
二、打印类:
public class PrintCopy
{
private int flag=1;
private int count=0;
public int getCount() {
return count;
}
public synchronized void printA() {
while(flag!=1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag=2;
count++;
System.out.print(count);
notifyAll();
}
public synchronized void printB() {
while(flag!=2) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag=3;
count++;
System.out.print(count);
notifyAll();
}
public synchronized void printC() {
while(flag!=3) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
flag=1;
count++;
System.out.print(count);
notifyAll();
}
}
class Print implements Runnable{
private PrintCopy pc;
public Print(PrintCopy pc) {
this.pc=pc;
}
public void run() {
//控制打印次数
while(pc.getCount()<13) {
if(Thread.currentThread().getName().equals("A")) {
pc.printA();
}
else if(Thread.currentThread().getName().equals("B")) {
pc.printB();
}
else if(Thread.currentThread().getName().equals("C")) {
pc.printC();
}
}
}
}
三、打印结果
A1B2C3A4B5C6A7B8C9A10B11C12A13B14C15