Disclosure: This text could include affiliate hyperlinks. If you buy, we could earn a fee.
with Vector we have to implement blocking utilizing wait
and notify and that is why now we have launched the produce(int i) and devour() methodology.
If
you see I’ve stored the buyer thread slightly gradual by permitting it to sleep for 50 Milliseconds to provide a possibility to the producer to fill the queue, which helps
to know that the Producer thread can be ready when Queue is full.
By the best way, in case you are new to multithreading in Java then I additionally recommend you be part of a course like Multithreading and Parallel Computing in Java from Udemy. It is a fantastic course to be taught the multithreading fundamentals and develop into a greater Java developer.
Java program to unravel Producer-Client Drawback in Java
programming language. On this program, now we have used the wait and notify methodology from
java.lang.Object class as a substitute of utilizing BlockingQueue for move management which makes implementing producer-consumer sample very easy.
Earlier than fixing the issue, let’s revisit what’s the producer-consumer downside first?
The secret’s to unravel the issue in such a approach that the producer ought to wait if the queue is full and the buyer ought to wait if the queue is empty which entails inter-thread communication.
This downside can be identified by completely different names within the technical world like a consumer-producer downside, bounded buffer downside, or a blocking queue downside. I extremely suggest you grasp this downside to enhance your concurrency expertise.
import java.util.logging.Stage;
import java.util.logging.Logger;
/**
* Java program to unravel Producer Client downside utilizing wait and
notify
* methodology in Java. Producer Client can be a preferred concurrency design
sample.
*
* @creator Javin Paul
*/
public class
ProducerConsumerSolution {
public static void
most important(String args[]) {
Vector sharedQueue = new Vector();
int measurement
= 4;
Thread prodThread = new Thread(new Producer(sharedQueue,
measurement), “Producer”);
Thread consThread = new Thread(new Client(sharedQueue,
measurement), “Client”);
prodThread.begin();
consThread.begin();
}
}
class Producer implements Runnable {
personal ultimate Vector sharedQueue;
personal ultimate int
SIZE;
public Producer(Vector sharedQueue, int measurement) {
this.sharedQueue = sharedQueue;
this.SIZE = measurement;
}
@Override
public void run() {
for (int i =
0; i < 7; i++) {
System.out.println(“Produced: “
+ i);
strive
{
produce(i);
} catch (InterruptedException
ex) {
Logger.getLogger(Producer.class.getName()).log(Stage.SEVERE,
null, ex);
}
}
}
personal void produce(int i) throws InterruptedException {
//wait if the queue is
full
whereas (sharedQueue.measurement() == SIZE) {
synchronized
(sharedQueue)
{
System.out.println(“The queue is full
“ + Thread.currentThread().getName()
sharedQueue.wait();
}
}
//producing component
and notify shoppers
synchronized
(sharedQueue)
{
sharedQueue.add(i);
sharedQueue.notifyAll();
}
}
}
class Client implements Runnable {
personal ultimate Vector sharedQueue;
personal ultimate int
SIZE;
public Client(Vector sharedQueue, int measurement) {
this.sharedQueue = sharedQueue;
this.SIZE = measurement;
}
@Override
public void run() {
whereas (true) {
strive
{
System.out.println(“Consumed: “
+ devour());
Thread.sleep(50);
} catch (InterruptedException
ex) {
Logger.getLogger(Client.class.getName()).log(Stage.SEVERE,
null, ex);
}
}
}
personal int devour()
throws InterruptedException {
//wait if the queue is
empty
whereas (sharedQueue.isEmpty()) {
synchronized
(sharedQueue)
{
System.out.println(“The queue is empty
“ + Thread.currentThread().getName()
measurement: “ + sharedQueue.measurement());
sharedQueue.wait();
}
}
//In any other case devour
component and notify the ready producer
synchronized
(sharedQueue)
{
sharedQueue.notifyAll();
return
(Integer)
sharedQueue.take away(0);
}
}
}
Output:
Produced: 0
The queue is empty Client is ready, measurement: 0
Produced: 1
Consumed: 0
Produced: 2
Produced: 3
Produced: 4
Produced: 5
The queue is full Producer is ready, measurement: 4
Consumed: 1
Produced: 6
The queue is full Producer is ready, measurement: 4
Consumed: 2
Consumed: 3
Consumed: 4
Consumed: 5
Consumed: 6
The queue is empty Client is ready, measurement: 0
When you have a look at the output there are a few factors which is value noting:
2. You’ll be able to see that the Client is ready when the queue is empty and the Producer is ready when the queue is full which is the anticipated conduct.
3. Any change to the shared object, right here sharedQueue which is a vector is going on contained in the synchronized block in order that adjustments made by one thread are seen to the opposite. Bear in mind every time a thread exit or enter a synchronized block, the reminiscence barrier is refreshed.
implement producer-consumer design patterns is a lot better due to its
simplicity and concise code. On the identical time, this downside is a superb
train to know the idea of the wait and notify methodology in Java.
- The right way to do inter-thread communication in Java utilizing wait-notify? (reply)
- The right way to pause a Thread in Java? (resolution)
- 5 Programs to Be taught Java Multithreading in-depth (programs)
- Distinction between risky, synchronized, and atomic variable in Java (reply)
- 10 Java Multithreading and Concurrency Finest Practices (article)
- Prime 5 Books to Grasp Concurrency in Java (books)
- Prime 50 Multithreading and Concurrency Questions in Java (questions)
- The right way to keep away from impasse in Java? (reply)
- Distinction between CyclicBarrier and CountDownLatch in Java? (reply)
- Distinction between ForkJoinPool and Executor Framework in Java(reply)
- 5 Important Abilities to Crack Java Interviews (expertise)
- Understanding the move of information and code in Java program (reply)
- The right way to be part of two threads in Java? (reply)
- Distinction between Executor and ExecutorService in Java? (reply)
- The right way to cease a Thread in Java? (reply)
- What’s Occurs Earlier than in Java Concurrency? (reply)
Thanks loads for studying this text thus far. When you like this instance of fixing the producer-consumer downside utilizing wait and notify in Java then please share it with your folks and colleagues. When you have any questions or suggestions then please drop a be aware.
P. S. – If you’re new however what to be taught Java Multithreading and Concurrency and in search of a free course to start out with then I additionally, recommend you try this superior free Java Multithreading course on Udemy.