Using multithreading to write producer-consumer relationships

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.