i have some small problem.
I hava some class Processor and Process. Process class have only name and value
Processor must calculate this value and display it. In turn, Processor implement Runnable interface
But i have a trouble. When I set process to my Processor, it begin to calculate value, but i want to start another thread with different value of process, and this value set to first thread too.
Here is code
package ua.edu.lp.controller;
import java.util.Random;
import ua.edu.lp.controller.processors.FirstProcessor;
import ua.edu.lp.controller.processors.MyBaseProcessor;
import ua.edu.lp.model.MyProcess;
import ua.edu.lp.model.Queue;
public class Computer {
private Queue<MyProcess> queue;
public void run() {
MyBaseProcessor myBaseProcessor = new FirstProcessor();
generateQueue();
for (int i = 0; i < queue.getQueue().size(); i++) {
MyProcess process = queue.get(i);
myBaseProcessor.setProcess(process);
Thread thread = new Thread(myBaseProcessor);
thread.start();
}
}
private void generateQueue() {
queue = new Queue<MyProcess>();
for (int i = 0; i < 10; i++) {
String name = "Process[" + (i + 1) + "]";
MyProcess myProcess = new MyProcess(name,
new Random().nextInt(10) + 1);
queue.add(myProcess);
System.out.println(myProcess.getName() + "\t"
+ myProcess.getValue());
}
}
}
BaseProcessor
package ua.edu.lp.controller.processors;
import ua.edu.lp.model.MyProcess;
public abstract class MyBaseProcessor implements Runnable {
protected MyProcess myProcess;
@Override
public void run() {
synchronized (myProcess) {
calculateValue();
}
}
protected abstract void calculateValue();
public synchronized MyProcess getProcess() {
return myProcess;
}
public synchronized void setProcess(MyProcess myProcess) {
synchronized (myProcess) {
this.myProcess = myProcess;
}
}
}
And FirstProcessor
package ua.edu.lp.controller.processors;
public class FirstProcessor extends MyBaseProcessor {
@Override
protected synchronized void calculateValue() {
System.out.println("First processor is working...");
int value = this.myProcess.getValue();
int result = (int) Math.pow(value, 2);
System.out.println("Pow of " + value + " = " + result);
System.out.println("First processor is free");
}
}
All project you can download from http://www.sendspace.com/file/5rlmkx
Make Processor stateless – remove field process and do something like this:
NOTE: Processor must do only common task – to run process, and process implement business logic and only process aware of calculations you’ve done.