import Java.util.arraylist;import java.util.List;/** * Created by the CCC on 16-4-27.*/ Public classTest { Public Static voidMain (string[] args) {gunclip clip=NewGunclip (); Producer P=NewProducer (clip); Customer C=Newcustomer (clip); P.start (); C.start (); }}/*first I'm going to have a magazine,*/classGunclip {//Mag Privatelist<integer> list =NULL;//used to put bullets . PrivateBoolean bfull =false;//It is important to understand the Boolean variable to indicate that it is not full//functions, like bullets in a magazine . PublicSynchronizedvoidput (List list) {if(!bfull) {//It means that the magazine is not full, so it's like a bullet inside. This. List =list; Bfull=true;//filled with bullets, turning the Boolean variable to TRUE indicates that the magazine is full.Notify ();//to wait for a bullet to take a bullet. } //The wait in the following try is the case when the magazine is full.//that is, a Boolean is true to pause this thread and wait for the bullet to be taken Try{wait (); } Catch(Exception e) {e.printstacktrace (); } } PublicSynchronizedvoid Get() { if(!bfull) {//if the magazine is not full then you can't take the bullet . Try{wait ();//The magazine is not full, so can not take, only wait, only the magazine is full to take}Catch(Exception e) {e.printstacktrace (); } } //Here's the magazine full, then I'll start taking the bullets.System. out. println ("\ n"+"the machine gun starts firing bullets:"+"\ n"); for(inti = List.size (); i >0; i--) { intj = (Integer) list.GetI1); System. out. println ("has shot out the first"+ j +"Bullets"); } //The magazine is empty, that is, no bullets, then only wait to refill,//so the Boolean goes false to indicate that it is not full, to notify the loaded thread to load the bulletsBfull =false; Notify (); }}//producers, that is, loaded bullets, below and bulletin board almost, to have a clip of the entityclassProducer extends Thread {PrivateGunclip clip; PrivateList<integer>list; Producer (gunclip clip) { This. Clip =clip; } Public voidrun () { for(inti =0; I <1; i++) {//Let it produce 3 magazines .List =NewArrayList (); System. out. println ("\ n"+"The machine gun starts to press into the bullet:"+"\ n"); for(intj =0; J < A; J + +) {List.add (J+1); System. out. println ("has been pressed into section"+ (J +1) +"Bullets"); } clip.put (list); } }}//consumers, firing bulletsclassCustomer extends Thread {PrivateGunclip clip; Customer (Gunclip clip) { This. Clip =clip; } Public voidrun () { while(true) {clip.Get(); } }}
The above code mainly introduces the Java multithreading solution to the producers of consumer problems, examples of Java using multi-threading method to solve the problem of producer consumers of the relevant skills, the need for friends can refer to the next
Java multithreading solves producer consumer problems