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:9
we 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 生产者消费者代码