java 生产者消费者代码_Java生产者和消费者代码
java 生產者消費者代碼
This also helps us to understand the concept of synchronised multi-threading in java, the basic work of our code is that the producer will produce a thread and load it into the memory and after producing the producer thread we would be loading the consumer thread to produce a consumable thread which will consume the value of the produce thread.
這也有助于我們理解Java中同步多線程的概念,我們代碼的基本工作是,生產者將產生一個線程并將其加載到內存中,并且在產生了生產者線程之后,我們將消費者線程加載到生產消耗性線程,它將消耗生產線程的值。
We would basically be creating two classes named as producer and consumer class.
我們基本上將創建兩個名為生產者和消費者類的類。
The producer class will be running a producer thread which is defined as the put method and after running of producer thread we will use consumer class to run the consumer thread which is basically the get method.
生產者類將運行定義為put方法的生產者線程,并且在運行生產者線程之后,我們將使用消費者類來運行消費者線程,該消費者線程基本上是get方法。
Below is the java code written for the same
下面是針對相同代碼編寫的Java代碼
package cp;class value {int n;int value=0;synchronized int get(){if(value==0)try{wait(1000);}catch(InterruptedException e){System.out.println("Exception caught");}System.out.println("consumed the value:"+n);value=0;notify();return n;}synchronized void put(int n){if(value==1)try{wait(1000);}catch(InterruptedException e){System.out.println("exception");}this.n=n;value=1;System.out.println("produced:"+n);notify();} } class Produce implements Runnable {value first;Produce(value first){this.first=first; new Thread(this,"Produce").start();}public void run(){int i=0;while(i<10){first.put(i++);}} } class Consume implements Runnable {value second;Consume(value second){this.second=second ;new Thread(this,"Consum").start();}public void run(){int i=0;while(i<10){second.get();i++;}} } public class Produceconsume {public static void main(String[] args){value first=new value();new Produce(first);new Consume(first);} }Output
輸出量
produced:0 consumed the value:0 produced:1 consumed the value:1 produced:2 consumed the value:2 produced:3 consumed the value:3 produced:4 consumed the value:4 produced:5 consumed the value:5 produced:6 consumed the value:6 produced:7 consumed the value:7 produced:8 consumed the value:8 produced:9 consumed the value:9we have used a while loop here to create 10 producer threads and their respective consumer threads. Hope you have understood the basic concept of producer and consumer threads, there are numerous codes available for producer and consumer threads online, once you develop the understanding you can write your own code too. Have a great day ahead and happy learning.
我們在這里使用了while循環來創建10個生產者線程及其各自的使用者線程。 希望您已經了解了生產者線程和使用者線程的基本概念 ,在線上有許多代碼可用于生產者線程和使用者線程,一旦您了解了,您也可以編寫自己的代碼。 祝您有美好的一天,學習愉快。
翻譯自: https://www.includehelp.com/java-programs/producer-and-consumer-code-in-java.aspx
java 生產者消費者代碼
總結
以上是生活随笔為你收集整理的java 生产者消费者代码_Java生产者和消费者代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Scala山脉
- 下一篇: java double方法_Java D