Using Java multithreading technology to design a program that complies with producer and consumer issues: operating a chamber with a maximum capacity of 12 bullets, the producer thread is a press-in thread that constantly presses bullets into the barrel; the consumer thread is a shot thread that constantly shoots bullets from the barrel.
public class Shengchanzhexiaofeizhe {public static void main (string[] args) {Container c = new Container (); Bulletproducer producer = new Bulletproducer (c); Bulletconcumer consumer = new Bulletconcumer (c); thread T1 = new Thread (producer); Thread t2 = new Thread (consumer); T1.start (); T2.start ();}} Bullet class, ID is ordinal class bullet{int ID; Bullet (int id) {this.id = ID;} Rewrite the ToString method for easy display of bullet numbers. @Overridepublic String toString () {return "+id+" "Bullet";}} Loaded container, with a certain amount of space, containing bullets and bullets synchronized method (is a stack), the method needs to determine the stack empty and full, and use the waiting wake mechanism control. Class container{bullet[] arr = new Bullet[12];int index = 0;public synchronized void push (Bullet Bullet) {while (Index==arr. Length) {try {this.wait ();} catch (Interruptedexception e) {e.printstacktrace ()}} This.notify (); Arr[index] = bullet;index++;} Public synchronized Bullet POPs () {while (index==0) {try {this.wait ()} catch (Interruptedexception e) {e.printstacktrace ( );}} This.notify (); Index--;return arr[index];}} The producer, which needs to be executed by a thread to implement the Runnable interface, initializes the bullet container in the Run method, constantly builds the bullet object and push it into the container, and outputs the bullet sequence number. Class Bulletproducer Implements Runnable{container C = null;public bulletproducer (Container c) {this.c = C;} public void Run () {int i = 0;while (true) {Bullet Bullet = new Bullet (++i); C.push (Bullet); SYSTEM.OUT.PRINTLN ("Loaded" +bullet);}}} Consumers, too, have implemented runnable, build containers, keep pop bullets from containers, and output bullet numbers. Class Bulletconcumer implements Runnable{container C = Null;public Bulletconcumer (Container c) {this.c = C;} public void Run () {while (true) {Bullet Bullet = C.pop (); System.out.println ("->->->->->-> launch" +bullet);}}
Review of thread producer consumers