This discussion is archived
1 Reply Latest reply: Feb 1, 2012 2:59 AM by 911503 RSS

Fork Join Framework Help

887502 Newbie
Currently Being Moderated
Hello,

I've been reading into the Fork/Join Framework. From what i have read so far the Fork Join Framework is brilliant. It offers a solution for true multicore processing. However im struggling to get my head around how you would use it to execute two different tasks. For example i have written the following very simple application using Threads. As the methods below do not return a value i know that RecrusiveAction would be used from the Fork Join Framework, however im not sure how to implement.

package threads;
import java.util.concurrent.Semaphore;
/**
*
* @author steven.haynes
*/
class Queue {

static Semaphore semConsumer = new Semaphore(0);
static Semaphore semProducer = new Semaphore(1);

String displayText;

String get() {
try {
semConsumer.acquire();
} catch (InterruptedException e) {}

System.out.println("Got: " + displayText);
semProducer.release();
return displayText;
}

void put(String displayText) {
try {
semProducer.acquire();
} catch (InterruptedException e) {}

this.displayText = displayText;
System.out.println("Put: " + displayText);
semConsumer.release();
}
}

class Producer implements Runnable {
Queue queue;

Producer(Queue queue) {
this.queue = queue;
new Thread(this, "Producer").start();
}

public void run() {
while (true) {
queue.put("Hello World");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
}
}
}

class Consumer implements Runnable {
Queue queue;

Consumer(Queue queue) {
this.queue = queue;
new Thread(this, "Consumer").start();
}

public void run() {
while (true) {
queue.get();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {}
}
}
}

class Concurrent {
public static void main(String args[]) {

System.out.println("Starting threads. Press Ctrl + C to exit.");

Queue queue = new Queue();
new Producer(queue);
new Consumer(queue);
}
}

Thanks,

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points