Multithreading is a very important application, this section describes the synchronization problem in multi-threading
Public classThreaddemo { Public Static voidMain (string[] args) {Resource R=NewResource (); Producer P1=NewProducer (R); Consumer C1=NewConsumer (R); NewThread (p1). Start (); NewThread (p1). Start (); NewThread (C1). Start (); NewThread (C1). Start (); }}/*Resource Class*/classResource {PrivateString name; Private BooleanFlag =false;//Resource Presence Tag//Production Resources Public synchronized voidset (String name) { while(flag) {Try { This. Wait (); } Catch(Exception e) {e.printstacktrace (); } } This. Name =name; System.out.println (Thread.CurrentThread (). GetName ()+ "creator" +name); Flag=true; This. Notifyall (); } //Consumer Resources Public synchronized voidget () { while(!flag) { Try { This. Wait (); } Catch(Exception e) {e.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName ()+ "Consumer" +name); Flag=false; This. Notifyall (); }}/*Producer Class*/classProducerImplementsRunnable {PrivateResource R; PublicProducer (Resource r) { This. R =R; } Public voidrun () { while(true) {R.set (Goods); } }}/*Consumer class*/classConsumerImplementsRunnable {PrivateResource R; PublicConsumer (Resource r) { This. R =R; } Public voidrun () { while(true) {r.get (); } }}
The above code enables synchronization and resolves a factory production problem that generates a single consumption.
Java Advanced-producer consumer issues