Package Ace;import java.util.arraylist;import Java.util.timer;import java.util.timertask;/** * Write producer-Consumer relationships with multithreading */ public class Productionandconsumption {private static arraylist<string> products = new arraylist<string> (); Product private static int index = 0; Product number public static void main (string[] args) {//producer thread final thread t1 = new Thread (new Runnable () {//every 5 seconds production of a product public voi D run () {//Start a production task New Timer (). Schedule (new TimerTask () {public void run () {synchronized (product) {String Product1 = "P "+ index++, product2 =" P "+ index++, product3 =" P "+ index++; System.out.println ("produced Products:" + Product1 + "," + Product2 + "," + product3 ");p Roducts.add (product1);p roducts.add (PRODUCT2); Products.add (PRODUCT3);}}, 1000, 5000); 1s after starting the task, after each 5s execution}});//consumer thread final thread t2 = new Thread (new Runnable () {//per second consume one product public void run () {//Start a production task new Timer (). Schedule (new TimerTask () {public void run () {synchronized (products) {if (products.size () > 0) {System.out.pri Ntln ("Consumption of Products:" + PRoducts.get (0));p roducts.remove (0);} else {System.out.println ("No product can be consumed");}}}, 1000, 1000); 1s after the start of the task, followed by one per second}}); T1.start (); T2.start ();}}
Using multithreading to write producer-consumer relationships