Producer-Consumer Problem with 2 processes in Java - java

I got task from my professor related to Producer-Consumer problem.
The task is implement Producer-Consumer process, but
first process should increase its value by 5 each time
second process should divide its value by 2 each time.
I found some examples of code, but nothing about multiple processes. Here is one of them.
--
// Java program to implement solution of producer
// consumer problem.
import java.util.LinkedList;
public class Threadexample {
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();
// Create producer thread
Thread t1 = new Thread(new Runnable() {
#Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Create consumer thread
Thread t2 = new Thread(new Runnable() {
#Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start both threads
t1.start();
t2.start();
// t1 finishes before t2
t1.join();
t2.join();
}
// This class has a list, producer (adds items to list
// and consumber (removes items).
public static class PC {
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
// Function called by producer thread
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size() == capacity)
wait();
System.out.println("Producer produced-"
+ value);
// to insert the jobs in the list
list.add(value++);
// notifies the consumer thread that
// now it can start consuming
notify();
// makes the working of program easier
// to understand
Thread.sleep(1000);
}
}
}
// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size() == 0)
wait();
// to retrive the ifrst job in the list
int val = list.removeFirst();
System.out.println("Consumer consumed-"
+ val);
// Wake up producer thread
notify();
// and sleep
Thread.sleep(1000);
}
}
}
}
}
Output:
Producer produced-0
Producer produced-1
Consumer consumed-0
Consumer consumed-1
Producer produced-2
I am not sure if I understand my task completely. Is it possible to implement given task on this code? I want you to give me some suggestions or any sources, so I can understand what to do.
Thank you all in advance!

If I correctly understand your problem from your description, you should change the field's value from two threads. You would like to create a class-level field and two synchronized methods for changing his value after that create two threads and call from them both operations alternately. I think you can write that:
public class Solution0 {
private volatile int count;
public synchronized void increment() throws InterruptedException {
count = count + 5;
Thread.sleep(1000);
notifyAll();
wait();
}
public synchronized void divide() throws InterruptedException {
count = count / 2;
Thread.sleep(1000);
notifyAll();
wait();
}
public static void main(String[] args) {
Solution0 solution = new Solution0();
Thread t1 = new Thread(() -> {
try {
while (true){
solution.increment();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2 = new Thread(() -> {
try {
while (true){
solution.divide();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
}
}
Also, you can change the type of field count from int to double, if you need a real number.

Related

Java - two threads with wait() and notify()

I am new to Java programming. i want to run two threads using wait() and notify(). But I cant use task flags for thread synchronization,sleep, yield or wait(parameter).I wrote it, but i had to use sleep. can someone help me to change it to without sleep.
This is my main class
public class mainClass{
public static void main(String args[]) throws InterruptedException {
final Processor processor = new Processor();
for(int i=0; i<100; i++){
final int z = i;
Thread trainer = new Thread(new Runnable(){
public void run(){
try{
processor.produce(z);
}catch(InterruptedException e){
e.printStackTrace();
}
}
});
Thread sportsman = new Thread(new Runnable(){
public void run(){
try{
processor.consume(z);
}catch(InterruptedException e){
e.printStackTrace();
}
}
});
trainer.start();
sportsman.start();
trainer.join();
sportsman.join();
}
System.out.println("100 Tasks are Finished.");
}
}
this is my second class.
public class Processor {
public void produce(int n) throws InterruptedException {
synchronized (this){
System.out.println("Trainer making " + (n+1) + " Task..." );
wait();
System.out.println("");
}
}
public void consume(int m) throws InterruptedException {
Thread.sleep(1);
//I want to run the code without using sleep and get same output
synchronized (this){
System.out.println("Sportman doing " + (m+1) + " Task...");
notify();
}
}
}
this is my output.
Trainer making 1 Task...
Sportman doing 1 Task...
Trainer making 2 Task...
Sportman doing 2 Task...
.
.
.
Trainer making 99 Task...
Sportman doing 99 Task...
Trainer making 100 Task...
Sportman doing 100 Task...
100 Tasks are Finished.
thank you. my english is bad. sorry for it.
Hints:
The correct use of wait involves waiting for something specific to happen. The correct implementation is something like this
synchronize (x) {
while (!x.itHasHappened()) {
x.wait(); // for it to happen
}
}
The loop is necessary since it is possible to get spurious notifies on a primitive lock.
In your specific example, ask yourself what must wait for what to happen. I think you've got it wrong. What is produce(N) actually waiting for, and why?
In mainClass you created 100 times two threads, I think you should create two threads only and in those two threads run the loop 100 times.
Probably you needed to do something like this...
The producer should create together 100 task (one at a time) and wait after each task for the consumer to be done.
The consumer should wait for a task and notify the producer when finished with the current task, them wait for the next task.
So your mainClass should look like this, loops should be in the producer() and consumer() methods.
public class mainClass {
public static void main(String args[]) throws InterruptedException {
final Processor processor = new Processor();
Thread trainer = new Thread(new Runnable() {
public void run() {
try {
processor.produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread sportsman = new Thread(new Runnable() {
public void run() {
try {
processor.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
trainer.start();
sportsman.start();
trainer.join();
sportsman.join();
System.out.println("100 Tasks are Finished.");
}
}
And the Processor maybe something like this...
public class Processor {
private int taskNo = 0; // the number of the current task
// (0 = there is no task, but will be)
// (-1 = there won't be more task)
public void produce() throws InterruptedException {
synchronized (this) {
for (int i = 0; i < 100; i++) {
taskNo = i + 1; // making a task number (i+1)
System.out.println("Trainer making " + taskNo + " Task...");
notify(); // notifies the consumer that the task was made
wait(); // and waiting the consumer to finish... zzzz...
System.out.println("");
}
taskNo = -1; // there will be no more task
notify(); // notify the consumer about it
}
}
public void consume() throws InterruptedException {
synchronized (this) {
do {
if (taskNo == 0) {
wait(); // there is no task to do, waiting... zzzz...
}
if (taskNo != -1) {
System.out.println("Sportman doing " + taskNo + " Task...");
taskNo = 0; // sets the task to done
notify(); // notifies the producer that the task was done
}
} while (taskNo != -1);
}
}
}
Typically there is a queue instead of the taskNo variable, where the producer puts tasks and the consumer takes tasks from in. But in your case the queue can have only 1 task at a time, because the producer should wait for the consumer to finish. So you can use a simple variable (taskNo) instead of a queue.

Producer Consumer Misunderstanding in Threading

I want the ProducerThread to produce random values upto 10 and then expect ConsumerThread to consumer those values of Queue. Somewhere Producer is generating adding the values more than once. I have a concept that when we call notify on an object than that Thread would release lock and give chance to Thread which was expecting updation.
Here is the code, please correct my understanding.
public class ProducerThread extends Thread {
Queue<Integer> values;
ProducerThread(Queue<Integer> values) {
this.values = values;
}
public void run() {
while(true) {
synchronized(values) {
double totalValues = Math.random()*10;
System.out.println("Going to populate total values:" + totalValues);
for (int i = 1; i <= totalValues; i++) {
values.add(i);
System.out.println("Value updated: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
values.notify();
}
}
}
}
public class ConsumerThread extends Thread {
Queue<Integer> values;
ConsumerThread(Queue<Integer> values) {
this.values = values;
}
#Override
public void run() {
while(true) {
synchronized (values) {
try {
// Consumer Thread waits until values are populated by Producer Thread
if(values.isEmpty()) {
values.wait();
}
Iterator<Integer> iterateValues = values.iterator();
System.out.println("Going to consume values: " + values.size());
while (iterateValues.hasNext()) {
Integer removedValue = iterateValues.next();
System.out.println("Value deleted: " + removedValue);
}
values.clear();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class Test {
public static void main(String[] args) {
Queue<Integer> values = new LinkedList<Integer>();
ProducerThread producer = new ProducerThread(values);
ConsumerThread consumer = new ConsumerThread(values);
consumer.start();
producer.start();
}
}
Aha! You have encountered the dreaded race condition!
Immediately after notify returns in your ProducerThread, said thread still has the lock. The ConsumerThread, woken up by the notify, will see that the lock is not available, and will wait until it becomes available.
Then the ProducerThread gives up the lock, it will then enter a race with the ConsumerThread to take that lock back (ProducerThread by way of re-entering the synchronized block, and ConsumerThread by means of having to return from wait). There is no guarantee which of these will win.
If you want your ProducerThread to wait for the items to be consumed before producing more, you should consider another wait/notify for that scenario.
EDIT: This image might help to explain things a bit more clearly.

wait for N-1 out of N threads to end, then issue an instruction for the last thread

So, i apologize for the title. It's quite hard to explain in one sentence what i would like to do if you have no idea on how it is called.
So assume i can only use primitive thread functions (wait, notify, no concurrent package)
The program has 3 threads, all of them are the same and are called by the main thread. They behave normally until one of the three get an exception and so it must wait for the end of the remaining 2 threads in order to start a recovery process.
I was thinking about a static variable but I'm not really sure about it, i would love to keep it as simple as possible.
Each thread starts at the same time.
I don't see any reason why you can't use a static variable like you suggest. Here's how I would do it with an inner class...
private static boolean running = true;
public void test26546397() {
while (true) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
Thread t3 = new Thread(new MyRunnable());
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
running = true;
// Do recovery
}
}
public class MyRunnable implements Runnable {
#Override
public void run() {
while (running) {
try {
// doStuff
} catch (Exception ex) {
running = false;
}
}
}
}
I would of course replace the while (true) with something a little more suitable.
I think you need java.concurrent.CountdownLatch, however if the java.concurrent package is not available to you can code this yourself using Object.wait/notify and synchronized blocks.
The latch can then be decremented in a finally {} on each Thread, this will be run if the Thread completes, or an exception occurs.
Your main program then just needs to wait for count to become 0.
public class StackOverflow26546397 {
static class CountdownLatch {
private int count;
private Object monitor = new Object();
public CountdownLatch(int count) {
this.count = count;
}
public void countDown() {
synchronized (monitor) {
count--;
monitor.notifyAll();
}
}
public void await() throws InterruptedException {
synchronized (monitor) {
while (count > 0) {
monitor.wait();
}
}
}
}
static class Job implements Runnable {
private CountdownLatch latch;
public Job(CountdownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
try {
// do work.
Thread.sleep((long) (Math.random() * 3000d));
} catch (InterruptedException e) {
//
} finally {
latch.countDown();
}
}
}
public static void main(String[] args) throws InterruptedException {
CountdownLatch latch = new CountdownLatch(3);
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
new Thread(new Job(latch)).start();
latch.await();
System.out.println("All threads finished");
}
}
Not sure what you are trying to do but this is as simple as I can think of (just native concurrency):
Create a static or shared volatile boolean
private static volatile boolean exceptionOccured=false
Set the above to 'true' when exception occurs:
....}catch(Exception e){
exceptionOccured=true;
}
Check this periodically in you normal thread flow:
if (exceptionOccured)
//enter you synchronized call here
the synchronized method could look something like:
public synchronized void checkAndRecover(){
//decrement a counter or other logic to identify which is the last Thread and then
//perform any recovery logic
}

Having troubles with threads and semaphors in JAVA

I am new to threading and semaphors, and I have some problem in synchronizing threads. For example, in the following code I want to do a pretty simple thing. To let one thread run, while other waits. For example, if it starts with the first thread, I want the second to wait for the first one to finish and then start. I really don't know what am I doing wrong.
Here is the code :
import java.io.*;
import java.util.concurrent.Semaphore;
public class ThreadTest {
public static void main(String[] args) throws InterruptedException {
Semaphore binaren = new Semaphore(1);
Runnable t1 = new T2(binaren);
Thread a = new Thread(t1);
Thread a2 = new T1(binaren);
System.out.println(binaren.availablePermits());
a.start();
a2.start();
}
}
class Work {
private static int a = 4;
public synchronized static void QQR(String s1)
{
for(int i=0;i<100;i++)
System.out.println(s1+" : "+(a++));
}
}
class T1 extends Thread
{
Semaphore sem;
public T1(Semaphore s1)
{
sem=s1;
}
public void run()
{
synchronized(this) {
if(!sem.tryAcquire()){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Work.QQR("T1");
sem.release();
notifyAll();
}
}
}
class T2 extends Thread
{
Semaphore sem;
public T2(Semaphore s1)
{
sem=s1;
}
#Override
public void run() {
synchronized(this) {
if(!sem.tryAcquire()){
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Work.QQR("T2");
sem.release();
notifyAll();
}
}
}
The problem is that notify and notifyAll only wake up threads holding locks on the monitor being notified. But the t1 and t2 instances are waiting on themselves and are never awoken. You can have them wait on the semaphore for this simple test or introduce a new shared object to see how it works.
Use
sem.wait();
and
sem.notifyAll();
You can use Thread.join() on the first thread so that second thread will wait till the execution of this instance is not completed.

Running the more than two threads in a particular order

I want the threads to run in a particular order. Suppose I have three thread T1, T2, T2 .
T1 prints 0
T2 prints 1
T3 prints 2
I want the output in the order 0 1 2, 0 1 2 for certain number of time.
If there are two threads T1 and T2. Printing 0 1, 0 1... can be done using Producer-Consumer Problem using synchronization.
Create a class UnitOfWork:
public class UnitOfWork implements Runnable
{
String text;
public UnitOfWork(String text){
this.text = text;
}
public void run(){
System.out.println(text);
}
}
And then create a single thread executor service:
ExecutorService executor = ExecutorService.newSingleThreadExecutor();
which you will use like this:
UnitOfWork uow0 = new UnitOfWork("0");
UnitOfWork uow1 = new UnitOfWork("1");
UnitOfWork uow2 = new UnitOfWork("2");
for(int i = 0; i < 5; i++){
executor.submit(uow0);
executor.submit(uow1);
executor.submit(uow2);
}
When you are unhappy with the single thread, you can start using multiple thread executor service, which will in fact run tasks concurrently.
Using the method join() in the thread class you can achieve this.
The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.
Like sleep, join responds to an interrupt by exiting with an InterruptedException.
Use Thread.join to ensure it terminates before the next thread starts.
public static void main(String[] args) throws InterruptedException {
final Thread th1 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Thread 1");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread th2 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Thread 2");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread th3 = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("Thread 3");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
th1.start();
th1.join();
th2.start();
th2.join();
th3.start();
}
This is a minimalist piece of code which does literally what you asked for. It relies on the wait-notify mechanism.
I stand by my assesment that you do not need any threads to meet your requirement. A simple loop which prints 0-1-2 is all you really need.
import static java.lang.Thread.currentThread;
public class A {
static int coordinator, timesPrinted;
static final int numThreads = 3, timesToPrint = 300;
public static void main(String[] args) {
for (int i = 0; i < numThreads; i++) {
final int myId = i;
new Thread(new Runnable() { public void run() {
while (true) synchronized (A.class) {
if (coordinator%numThreads == myId) {
System.out.println(myId+1);
coordinator++;
if (timesPrinted++ > timesToPrint) currentThread().interrupt();
A.class.notifyAll();
}
try {A.class.wait();} catch (InterruptedException e) {break;}
}
}}).start();
}
}
}

Categories