0

I am trying to write a multithreaded code. But seriously I can't understand from where can I start. My head is banging also. Please help me.

My task is,

  1. There is one queue of length 1, known as pending_tasks, that contains tasks which requires some processing.
  2. There is another queue of length 1, known as completed_tasks, that contains tasks which completes processing., and ready to deliver.

My implementation thinking,

  1. Firstly make two blocking queues, pending_tasks and completed_tasks.
  2. One thread(producer) always listening for tasks that comes from outside, if gets put into pending_tasks.
  3. One thread(consumer) always ready to take tasks from pending_tasks and starts processing , and after that put into into completed_tasks.
  4. Then again comes to pending_tasks, and whenever any tasks come, start the same processing.
  5. Basically, its a single producer-single consumer problem.

My confusion,

I know that it can be code by using ArrayBlockingQueue and Mutex. But I didn't understand how can I start this. I have good understanding of mutex, I read about mutex from this link, and have good understanding of blockingQueue also, as I read lots of questions on this site.

Can you please give me some implementation guidance, so that I can write this multi-threaded code.

I already wrote some code for the same, but that is not achieve the final goal of my task.

Thanks in advance. Looking for your kind reply.

EDIT NO. 1

Please see my below code. This code works fine, but this code has one functionality missing. Please help me to add that, give some guidance to do that.

Functionality is,

  1. When producer thread puts some value in pending_task queue, then it waits for some time there. If in that time consumer gives the result to consumer, then its OK. Otherwise, it says time out, and producer takes another value and pput that in pending_task queue, and the same process starts.

Please help me in adding above functionality. I think we have to communicate between producer thread and consumer thread, and thread communication is done by using Mutex(I think). Please help me implementing the same

My code,

MultiThread Class

package multithread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class MultiThread {

    public static BlockingQueue<Integer> pending_task;
    public static BlockingQueue<Integer> completed_task;

    public MultiThread(int length) {
        pending_task = new ArrayBlockingQueue<Integer>(length, true);
        completed_task = new ArrayBlockingQueue<Integer>(length, true);
    }
}

Producer Class

package multithread;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Producer implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("PRODUCER: Try to put value  " + i + "  in the pending queue");
                MultiThread.pending_task.put(i);
                System.out.println("PRODUCER: Successfully put value  " + i + "  in the pending queue, now its turn to consumer");
            } catch (InterruptedException ex) {
                Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

Consumer Class

package multithread;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Consumer implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("CONSUMER: Try to take value from the pending queue");
                int val = MultiThread.pending_task.take();
                System.out.println("CONSUMER:  Successfully take value, and that is   " + val);
                System.out.println("CONSUMER: Processing starts");
                Thread.sleep(1000);
                System.out.println("CONSUMER: Processing ends");
                System.out.println("CONSUMER: Try to put that  that value in  completed queue, and the value is   " + val);
                MultiThread.completed_task.put(val);
                System.out.println("CONSUMER: Successfully put into completed queue");

                //Serve this value to the corresponding user
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}

DeliveryBoy Class

package multithread;

import java.util.logging.Level;
import java.util.logging.Logger;

public class DeliveryBoy implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("DELIVERYBOY: Waiting for the value near completed queue");
                int val = MultiThread.completed_task.take();
                System.out.println("DELIVERYBOY:  Succesfully take value from completed queue and the vlue is  " + val);
                //Serve this value to the corresponding user
            } catch (InterruptedException ex) {
                Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }
}

Test Class

package multithread;

public class Test {

    public static void main(String[] args) {
        // TODO code application logic here
        MultiThread ml = new MultiThread(1);
        new Thread(new Producer()).start();
        new Thread(new Consumer()).start();
        new Thread(new DeliveryBoy()).start();
    }
}
devsda
  • 4,112
  • 9
  • 50
  • 87
  • 3
    Your question is very likely to be closed unless you post your current code and formulate a question around why that doesn't work. Currently, your question is very vague and open-ended and can only be answered by someone writing the whole thing for you. – Duncan Jones Apr 18 '13 at 10:41
  • Your mutex link is fairly old. While you can still use wait/notify for consumer/producer patterns, there are more useful and higher-level solutions. I suggest you read http://docs.oracle.com/javase/tutorial/essential/concurrency/. – Ralf H Apr 18 '13 at 11:29
  • @DuncanJones I added my code in question. Please see that – devsda Apr 18 '13 at 12:44
  • @DuncanJones Please see my code, and give some guidance, please. – devsda Apr 18 '13 at 16:40
  • Please see EDIT NO. 1, it shows my code, and some functionality , that I want to add. Please suggest some expert advise. How can I do that. If possible please give some implementation guide. – devsda Apr 19 '13 at 07:16

1 Answers1

1

From ArrayBlockingQueue#put

public void put(E e) throws InterruptedException

Inserts the specified element at the tail of this queue, waiting for **space to become available if the queue is full

From ArrayBlockingQueue#take

public E take() throws InterruptedException

Description copied from interface: BlockingQueue Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

So all you need to do is call these methods from your threads.
Try this (study the javadoc) and when you have a more specific problem you can ask again.

Cratylus
  • 52,998
  • 69
  • 209
  • 339
  • The thing that you explain in answer is already known to me. I feel that I am already good in theory perspective. But I am unable to convert that into code. I made some code(see the updated part of question), but that have lots of issues , please help me to solve these. and yes I want to add mutex concept also in that. – devsda Apr 18 '13 at 12:54
  • This is the question, how can I implement this, there is something missing in thia, please just guide me, how can I implement threading here , and mutex also in this. – devsda Apr 18 '13 at 18:09
  • @devsda:Check this out: http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html – Cratylus Apr 18 '13 at 18:16
  • According to this page, I have to make different classes for prodcer, consumer ? But actually I want this all performs in the same module of one class. Can I do that ? – devsda Apr 19 '13 at 04:56
  • Please see EDIT NO. 1, it shows my code, and some functionality , that I want to add. Please suggest some expert advise. How can I do that. If possible please give some implementation guide. – devsda Apr 19 '13 at 07:16
  • You need a `Runnable` for `Producer` and a `Runnable` for `Consumer`.These will share the same instance of `BlockingQueue`. You start them both and one will place to the queue the other will remove concurrently as they are *run* by different threads you *started* – Cratylus Apr 19 '13 at 12:44
  • I have already done the same thing, that you said, and posted in the `Edit no 1`. Please see that code. I want to add one functionality , I also mentioned that also in Edit no. 1. – devsda Apr 20 '13 at 09:45
  • Please See my Edit no.1, please help me. – devsda Apr 22 '13 at 05:27