packagepracticeagagin;public classTest {//private static Object OddTask;
public static voidmain(String args[]){
PrintNumber printNum= new PrintNumber(100);
EvenTask evenTask= newEvenTask(printNum);
OddTask oddTask= newOddTask(printNum);
Thread thread1= newThread(evenTask);
Thread thread2= newThread(oddTask);
thread1.start();
thread2.start();
}
}packagepracticeagagin;public classPrintNumber {protected int upBound;//定义打印数字的上界
protected int currentNum=0;public PrintNumber(intupBound){this.upBound =upBound;
}public intgetNum(){returncurrentNum;
}
}packagepracticeagagin;//这个类的作用是方便代码重用,减少代码量//因为无论是打印奇数,还是打印偶数,他们的工作流程可以看作是一样的//看打印机有没有在使用,有的话阻塞自己//看打印机有没有在使用,没有的话,看是否是自己可以打印的数;是则打印-打印结束唤醒其它进程;不是则阻塞自己(这里不用去唤醒了,阻塞后又怎么能唤醒别人呢?);//数字奇偶的判断,交给数字类来完成;数字类也一样提高了程序的代码质量
abstract class PrintTask implementsRunnable {protectedPrintNumber printNum;publicPrintTask(PrintNumber printNum) {this.printNum =printNum;
}
@Overridepublic voidrun() {while (printNum.currentNum < printNum.upBound) {//还没到达上界持续打印//打印操作,使用打印机需要上锁,通过原子操作控制同步
synchronized (printNum) {//查看打印机有没有在使用;有的话,其它线程阻塞在外面//没有,既可以打印//查看自己是否可以打印
if(isShouldPrint()) {
System.out.println(Thread.currentThread().getName()+"打印了"+printNum.getNum());
printNum.currentNum++;
printNum.notifyAll();
}else{try{
printNum.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
}public abstract booleanisShouldPrint();
}packagepracticeagagin;public class EvenTask extendsPrintTask {//子类继承,也要定义下构造方法!
publicEvenTask(PrintNumber printNum) {super(printNum);
}public booleanisShouldPrint(){return printNum.currentNum%2==0;
}
}packagepracticeagagin;public class OddTask extendsPrintTask {publicOddTask(PrintNumber printNum){super(printNum);
}public booleanisShouldPrint(){return printNum.currentNum%2!=0;
}
}