javamultithreadingrunnableblockingqueue

Java peer-to-peer thread model, everyone wait for Job


This is a schoolwork. I am trying to create peer-to-peer Thread model:

http://www.informit.com/articles/article.aspx?p=169479&seqNum=5

Where the delegation model has a boss thread that delegates tasks to worker threads, in the peer-to-peer model all the threads have an equal working status. Although there is a single thread that initially creates all the threads needed to perform all the tasks, that thread is considered a worker thread and does no delegation. In this model, there is no centralized thread.

So my main thread willl create 5 threads, that start listening to my queue and also create jobs with main thread for 10 seconds. And since all threads must perform tasks, this thread must also wait for jobs. How can I do this?

BlockingQueue<Job> queue = new ArrayBlockingQueue<Job>(1000);

    Collection<Thread> workers = new ArrayList<Thread>();
    for(int i = 0; i < 5; i++) {
        Thread thread = new Thread(new Worker(queue));
        workers.add(thread);
        thread.start();
    }

    long endTime = System.currentTimeMillis() + 10000;
    Random r = new Random();
    while(System.currentTimeMillis() < endTime) {
        try {
            CalculateJob job = new CalculateJob(r.nextInt(50), r.nextInt(50), r.nextInt(50));
            queue.put(job);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }   

So my main thread will be working with creating threads, and workers are just sitting with queue.take().

Do I understand correctly that in peer-to-peer model, every thread must queue.take() or wait for jobs. If so, how can I do this? Any suggestions?


Solution

  • The article you linked to doesn't say how jobs are created. They probably mean they are created from elsewhere. Looking at the figures for the respective models, we see that:

    By using a ConcurrentQueue, you have actually implemented the peer to peer model.

    To summarize, the distinction they make is how threads coordinate the work, not how the work is created.