Java并发线程

时间:2015-04-27 17:56:32

标签: java multithreading concurrency

我正在尝试设置一个小型打印程序。 我有这样的代码,如果打印机纸张级别高于学生想要打印的页数,学生会尝试打印文档。 目前,学生无法打印文档,因为纸张级别低于打印所需的页数。此时printDocument()必须等待方法refilPaper()的notify(); 我怎么能这样做?

主要代码:

class classA
{
   public static void main ( String args[] )
   {
    // TODO code application logic here
        LaserPrinter printer = new LaserPrinter("MyPrinter", 1, 30, 50, 0);
        ThreadGroup students = new ThreadGroup("Students");
        ThreadGroup technicians = new ThreadGroup("Technicians");

        Student student1 = new Student(students, "User 1", printer);
        PaperTechnician paperTech1 = new PaperTechnician(technicians, "PaperTechnician1", printer);

        student1.start();
        paperTech1.start();

      while(true)
         {
             try
             {    student1.join();
                  paperTech1.join();
              }
             catch(InterruptedException ex){}
         }
   }
}

打印机代码:

private boolean available = false;

@Override
public synchronized void printDocument(Document document) {

    while(getPrinter_CurrentPaperLevel() <= document.getNumberOfPages() || getPrinter_ToonerLevel() <= document.getNumberOfPages())
    {
        try { 
             System.out.println("waiting for refill of something..");
             wait();
             } catch(InterruptedException e){ }
    }
    available = false;
    notifyAll(); 
    System.out.println(document);

}

public synchronized void refilPaper(){
   while ( available )
     {
     try {
         System.out.println("Not available");
         wait();
         } catch(InterruptedException e){ }
     }
     setPrinter_CurrentPaperLevel(ServicePrinter.SheetsPerPack);
     available = true;
     notifyAll();

}

任何帮助都会感激不尽。感谢

0 个答案:

没有答案