This article gives you the content is about the Java Consumer Problem Code analysis, there is a certain reference value, the need for a friend can refer to, I hope you have some help.
1. Resources
public class Resource {//The number of current resources int num = 0; Upper limit of current resource int size = 10; Consumer resources public synchronized void remove () {//If num is 0, there is no resource, you need to wait while (num = 0) {try { SYSTEM.OUT.PRINTLN ("Consumer enters Wait"); This.wait (); } catch (Interruptedexception e) {e.printstacktrace (); }}//If the thread can execute here, it indicates that resources have resources to consume num--; SYSTEM.OUT.PRINTLN ("Consumer thread:" + thread.currentthread (). GetName () + "--Number of resources:" + num); This.notifyall (); }//Production resource public synchronized void put () {//If the resource is full, it enters the blocking state while (num = = size) {try { System.out.println ("producer enters Wait"); This.wait (); } catch (Interruptedexception e) {e.printstacktrace (); }} num++; System.out.println ("Producer Thread:" + thread.currentthread (). GetName () + "--Number of resources:" + num); This.notifyall (); }}
2. Consumers
public class Consumer implements Runnable { private Resource Resource; Public Consumer (Resource Resource) { this.resource = Resource; } @Override public Void Run () { while (true) { resource.remove ()} } }
3. Producers
public class Producer implements Runnable { private Resource Resource; Public Producer (Resource Resource) { this.resource=resource; } @Override public Void Run () { while (true) { resource.put ()} } }
4. Testing
public class Testconsumerandproducer {public static void Main (string[] args) { Resource Resource = new Resource () ; Production line Producer p1 = new Producer (resource); Consumer thread Consumer c1 = new Consumer (resource); New Thread (p1). Start (); New Thread (C1). Start (); }}