I've a application which runs with two threads. The main thread runs in one infinity-while-loop:
while (true) {
try {
ArrayList<Info> infoList = zabbixHandler.APIRequest();
handleInfo.handleInformation(infoList);
Thread.sleep(5000);
}
}
The second thread, which uses more than 50% of my CPU, must be able to stop and run again, which I asked already with this question on Stack Overflow.
The solution works perfectly, but as I already said, it uses >50% of the CPU. Here are the two loops of the solution:
private volatile boolean finished = true;
public void run() {
Process p;
while (true) {
// loop until the thread is finished
while (!finished) {
try {
// let every lamp shine...
p = Runtime.getRuntime().exec(onCommand + "-green");
p.waitFor();
// ... for 0.5 seconds ...
Thread.sleep(500);
// ... then turn it off again ...
p = Runtime.getRuntime().exec(offCommand + "-green");
p.waitFor();
// ... and let the next lamp shine
p = Runtime.getRuntime().exec(onCommand + "-yellow");
p.waitFor();
Thread.sleep(500);
p = Runtime.getRuntime().exec(offCommand + "-yellow");
p.waitFor();
p = Runtime.getRuntime().exec(onCommand + "-red");
p.waitFor();
Thread.sleep(500);
p = Runtime.getRuntime().exec(offCommand + "-red");
p.waitFor();
p = Runtime.getRuntime().exec(onCommand + "-blue");
p.waitFor();
Thread.sleep(500);
p = Runtime.getRuntime().exec(offCommand + "-blue");
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
How could I reduce the use of CPU while retaining the functionality?
EDIT:
The finish
element will be changed by a getter and setter. Because it is volaitle, it shouldn't get complications.
Thread.sleep(milliseconds)
is a rough estimation only? \$\endgroup\$finished
change totrue
? \$\endgroup\$> 50%
of the time? \$\endgroup\$finished
get declared, and how is it modified. Will remove -1 when question is corrected. \$\endgroup\$