Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to synchronize methods in java?
    text
    copied!<p>i have some small problem. I hava some class <strong>Processor</strong> and <strong>Process</strong>. <strong>Process</strong> class have only name and value <strong>Processor</strong> must calculate this value and display it. In turn, <strong>Processor</strong> 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</p> <pre><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&lt;MyProcess&gt; queue; public void run() { MyBaseProcessor myBaseProcessor = new FirstProcessor(); generateQueue(); for (int i = 0; i &lt; 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&lt;MyProcess&gt;(); for (int i = 0; i &lt; 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()); } } } </code></pre> <p>BaseProcessor</p> <pre><code>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; } } } </code></pre> <p>And FirstProcessor</p> <pre><code>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"); } } </code></pre> <p>All project you can download from <a href="http://www.sendspace.com/file/5rlmkx" rel="nofollow">http://www.sendspace.com/file/5rlmkx</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload