Producer Consumers
1 classResource2 {3 PrivateString name;4 Private intCount = 1;5 Private BooleanFlag =false;6 7 Public synchronized voidset (String name)8 {9 while(flag)Ten Try{ This. Wait ();}Catch(Exception e) {} One This. Name = name+ "--" +count++; ASystem.out.println (Thread.CurrentThread (). GetName () + "... Producer ... "+ This. Name); -Flag =true; - This. Notifyall (); the } - - Public synchronized voidout () - { + while(!flag) - Try{ This. Wait ();}Catch(Exception e) {} +System.out.println (Thread.CurrentThread (). GetName () + "... Consumer ... "+ This. Name); AFlag =false; at This. Notifyall (); - } - } - - classProducerImplementsRunnable - { in PrivateResource Res; - to Producer (Resource res) + { - This. res =Res; the } * $ Public voidRun ()Panax Notoginseng { - while(true) the { +Res.set ("+tt+"); A } the } + } - $ classCustomerImplementsRunnable $ { - PrivateResource Res; - the Customer (Resource res) - {Wuyi This. res =Res; the } - Wu Public voidRun () - { About while(true) $ { - res.out (); - } - } A } + classProducercustomerdemo the { - Public Static voidMain (string[] args) $ { theResource r =NewResource (); the theProducer Pro =NewProducer (r); theCustomer con =NewCustomer (r); - inThread T1 =NewThread (pro); theThread t2 =NewThread (con); the About T1.start (); the T2.start (); the } the}View Code
Multithreading in Java (vi)