In the real development of multi-threaded communication problems with the following examples are more
Different places when the difference between if and while is only two threads of communication, using if is not a problem.
But there's a problem between multiple threads.
1 /*2 * This example is used to explain the situation of multiple producers and multiple consumers3 */4 5 /*6 * Resource Library7 */8 classResource9 {Ten PrivateString name; One Private intCount = 1; A Private BooleanFlag =false; - Public synchronized voidset (String name) { - the while(flag) - Try{ This. Wait ();} - Catch(Exception e) { - + } - This. Name = name + "--" + count++; +System.out.println (Thread.CurrentThread (). GetName () + "Production goods" + This. Name); AFlag =true; at This. Notifyall (); - - } - - - Public synchronized voidout () { in while(!flag) - Try{ This. Wait ();} to Catch(Exception e) { + - } theSystem.out.println (Thread.CurrentThread (). GetName () + "consumed" + This. Name); *Flag =false; $ This. Notifyall ();Panax Notoginseng } - the } + A /* the * Producer + */ - classProducerImplementsRunnable $ { $ PrivateResource Res; - Producer (Resource res) { - the This. res =Res; - }Wuyi Public voidrun () { the - while(true){ Wu -Res.set ("Toothpaste"); About } $ } - - - } A /* + * Consumer the */ - classConsumerImplementsRunnable $ { the the PrivateResource Res; the Consumer (Resource res) { the - This. res =Res; in } the Public voidrun () { the About while(true){ the res.out (); the } the } + } - Public classProducerconsumerdemo { the Bayi Public Static voidMain (string[] args) { the //TODO auto-generated Method Stub theResource res =NewResource (); - -Producer P1 =NewProducer (res); theProducer P2 =NewProducer (res); the theConsumer C1 =NewConsumer (res); theConsumer C2 =NewConsumer (res); - theThread T1 =NewThread (p1); theThread t2 =NewThread (p2); theThread t3 =NewThread (C1);94Thread T4 =NewThread (C2); the the T1.start (); the T2.start ();98 T3.start (); About T4.start (); - 101 102 103 }104 the}
Producer and consumer of communication between multithreading in Java (communication between multiple threads)