How to restart an update loop of an application - java

I am working on a drawing application, using Java and Swing. It has a constant update loop that runs constantly, as long as a boolean variable is set to true. The loop is located inside a thread.
It works fine, but now I want the loop to only run at certain times (only when the mouse is pressed), and otherwise not run. (Thus not wasting memory for nothing).
To stop the loop, I can simply set that variable to false. But my question is, how can I restart the loop after stopping it? Setting that variable back to true will not restart the loop. What would be a good way to do this?
EDIT: My (a little simplified) loop:
public void run(){
int TICKS_PER_SECOND = 50;
int SKIP_TICKS = 1000 / TICKS_PER_SECOND;
int MAX_FRAMESKIP = 10;
long next_game_tick = System.currentTimeMillis();
int loops;
boolean app_is_running = true;
while( app_is_running ) {
loops = 0;
while( System.currentTimeMillis() > next_game_tick && loops < MAX_FRAMESKIP) {
update();
next_game_tick += SKIP_TICKS;
loops++;
}
repaint();
}
}

Use Object.wait to suspend the thread when it isn't running. Have another thread call Object.notify to wake it up from its sleep.

To execute the thread body once every FRAME_RATE ms while being controllable by an externally defined Boolean, the run method could be structured as such:
public void run()
{
long delay;
long frameStart = System.currentTimeMillis();
// INSERT YOUR INITIALIZATION CODE HERE
try
{
while (true)
{
if (active) // Boolean defined outside of thread
{
// INSERT YOUR LOOP CODE HERE
}
frameStart += FRAME_RATE;
delay = frameStart - System.currentTimeMillis();
if (delay > 0)
{
Thread.sleep(delay);
}
}
}
catch (InterruptedException exception) {}
}
Additionally, if you want to eliminate the slight overhead of the constantly running loop (for a mostly inactive thread), the Boolean in the while loop could be replaced with a Semaphore object:
while (true)
{
semaphore.acquire(); // Semaphore defined outside thread with 1 permit
// INSERT YOUR LOOP CODE HERE
semaphore.release();
frameStart += FRAME_RATE;
delay = frameStart - System.currentTimeMillis();
if (delay > 0)
{
Thread.sleep(delay);
}
}
To stop the loop externally use semaphore.acquire(); to restart it use semaphore.release().

Related

can i limit number of onScrolled() method call per touch event in recyclerview?

How to be limit number of times call and runs method OnScrolled() in RecyclerView ?? Because there are a number of conditions in it, very much executing this code,Cause slowdown the application.
condition :
if (dy < 0 && mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() >= 10 && !mStateScrollTop) {
YoYo.with(Techniques.SlideInUp)
.duration(150)
.playOn(iv_go_to_top);
mStateScrollTop = true;
} else if (dy > 0 && mStateScrollTop) {
YoYo.with(Techniques.SlideOutDown)
.duration(150)
.playOn(iv_go_to_top);
mStateScrollTop = false;
}
I would do something like this:
onScrolled() {
synchronized(this) {
if(!ready)
return;
else
ready = false;
}
// your current onScroll body
}
And then you would launch a thread setting a ready variable to true in regular intervals. Something like this:
private void launchOnScrollThread() {
new Thread() {
#Override
public void run() {
// endless loop - maybe you would like to put some condition to end the loop
for(;;) {
ready = true;
Thread.sleep(100); // wait here for 100 milliseconds
}
}
}.start();
}
This would ensure that your current code in onScroll will be executed at most every 100 milliseconds, which should speed it up. Sorry that it's kind of a pseudocode, hope it makes sense to you and will be helpful.

How to run a Thread for a user specified amount of time?

Am creating a program that is based on mixing and making perturbation in a population containing solutions Vector.
So I created a for loop that stops after a certain time given by the user.
Inside the loop, am going to call 5 procedures and I thought that if i put each procedure in a thread will make the program making more solutions in a same time than calling normal methods.
Here 5 created the 5 threads, but when i start them the don't want to stop even if i use the Thread.stop, Thread.suspend, Thread.interrupt or Thread.destroy
Here is my code and could u help me with your ideas ?
I have inserted a new variable :
public volatile boolean CrossOpb = true;`
Here is my code:
Thread CrossOp = new Thread(new Runnable() {
public void run() {
while(CrossOpb == true){
int rdmCross2=(int) (Math.random() * allPopulation.size()) ; // Crossover 1st vector
int rdmCross1=(int) (Math.random() * allPopulation.size()) ;
Vector muted = new Vector();
Vector copy = copi((Vector) allPopulation.get(rdmCross2));
Vector callp = copi((Vector) allPopulation.get(rdmCross1));
muted = crossover(callp, copy);
System.out.println("cross over Between two Randoms ----------->");
affiche_resultat(muted);
allPopulation.add(muted);
}
}
});
The loop :
CrossOp.setDaemon(true);
int loop = 1;
long StartTime = System.currentTimeMillis() / 1000;
for (int i = 0; i < loop; ++i) {
loop++;
if (timevalue < ((System.currentTimeMillis() / 1000) - StartTime)) {
loop = 0;
CrossOpb = false;
}
CrossOp.start();
}
I already answered to a similar question. In that case, it was C#, but the concept is the same.
You must not kill threads. Threads must exit on their own will.
Just put a volatile boolean variable somewhere, and set it to true/false, when you want your thread to terminate, then, in the thread, replace the while (true) with a while (myVariable == true/false).
Anyway, you say:
Inside the loop, am going to call 5 procedures ant i thought that if i put each procedure in a thread will make the program making more solutions in a same time than calling normal methods.
Well, that's generally false. If the procedures are data-dependent (each of them depends on the results of the previous one), putting them on threads will change nothing. It might be smarter to put iterations in a pipeline, so that you have 5 threads executing steps of successive iterations. I'm not sure if that's possible for genetic algorithms, and anyway you'll have to handle some special case (e.g. a mutation, that alters the population of partially computed iterations).
How to run a Thread for a specific amount of time:
Here is the basic approach is to keep calculate how long the Thread has run and exit and return the result, which in our case here is details on how long the Thread executed.
NOTE: you must use System.nanoTime() as System.currentTimeMillis() will just return the same thing every time you call it in the method.
I use a Random number to calculate different lifetimes for each of the Callables so that you can see that they don't execute exactly for the time specified but they are very very close, and the variance of the delta is pretty consistent, at least on my machine.
Here a Gist of the code below for easier access.
package com.stackoverflow.Q18818482;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
public class Question18818482
{
public static Random RND;
static
{
RND = new Random();
}
public static void main(final String[] args)
{
try
{
final ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
final List<Future<String>> results = new ArrayList<>(10);
for (int i = 0; i < 10; i++)
{
results.add(es.submit(new TimeSliceTask(RND.nextInt(10), TimeUnit.SECONDS)));
}
es.shutdown();
while(!results.isEmpty())
{
final Iterator<Future<String>> i = results.iterator();
while (i.hasNext())
{
final Future<String> f = i.next();
if (f.isDone())
{
System.out.println(f.get());
i.remove();
}
}
}
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
catch (ExecutionException e)
{
throw new RuntimeException(e);
}
}
public static class TimeSliceTask implements Callable<String>
{
private final long timeToLive;
private final long duration;
public TimeSliceTask(final long timeToLive, final TimeUnit timeUnit)
{
this.timeToLive = System.nanoTime() + timeUnit.toNanos(timeToLive);
this.duration = timeUnit.toMillis(timeToLive);
}
#Override
public String call() throws Exception
{
while( timeToLive <= System.nanoTime() )
{
// simulate work here
Thread.sleep(500);
}
final long end = System.nanoTime();
return String.format("Finished Elapsed Time = %d, scheduled for %d", TimeUnit.NANOSECONDS.toMillis(timeToLive - end), this.duration );
}
}
}
Here is what one runs output looks like
NOTE: All times are in milliseconds
Finished Elapsed Time = 999, scheduled for 1000
Finished Elapsed Time = 2998, scheduled for 3000
Finished Elapsed Time = 5999, scheduled for 6000
Finished Elapsed Time = 1994, scheduled for 2000
Finished Elapsed Time = 8994, scheduled for 9000
Finished Elapsed Time = 6993, scheduled for 7000
Finished Elapsed Time = 6993, scheduled for 7000
Finished Elapsed Time = 5993, scheduled for 6000
Finished Elapsed Time = 5998, scheduled for 6000
After reading the whole last night about threads, i have discovered that the solution for my problem was not that hard.
The idea was to edit the condition of the stopping loop inside the thread so we control it by giving it a specific amount of time to run for it and here is my Example :
class ProcessorCordm extends Thread {
int runningtime;
public ProcessorCordm(int runningtime) {
this.runningtime = runningtime;
}
public void run() {
int loop = 1;
long StartTime = System.currentTimeMillis() / 1000;
for (int i = 0; i < loop; ++i) {
int rdmCross2 = (int) (Math.random() * allPopulation.size()); // Crossover 1st vector
int rdmCross1 = (int) (Math.random() * allPopulation.size());
Vector muted = new Vector();
Vector copy = copi((Vector) allPopulation.get(rdmCross2));
Vector callp = copi((Vector) allPopulation.get(rdmCross1));
muted = crossover(callp, copy);
System.out.println("cross over Between two Randoms ----------->");
affiche_resultat(muted);
addsolution(muted);
loop++;
if (timevalue < ((System.currentTimeMillis() / 1000) - StartTime)) {
loop = 0;
}
}
}
}
So if i want to run my Thread for 10 seconds i only need to :
ProcessorCoG CrossOpg = new ProcessorCoG(10);
And fo my case, I have to call many Threads simultaneously working for a specific TimeValue so i used the ExecutorServiceClass :
ProcessorCoG CrossOpg = new ProcessorCoG(timevalue);//extends Thread class
ProcessorCordm CrossOp = new ProcessorCordm(timevalue);//extends Thread class
ProcessorCordm CrossOp2 = new ProcessorCordm(timevalue);//extends Thread class
MutateGb MutGb = new MutateGb(timevalue);//extends Thread class
MutateRdm MutRdm = new MutateRdm(timevalue);//extends Thread class
MbsRdm MbsR = new MbsRdm(timevalue);//extends Thread class
ExecutorService executor = Executors.newFixedThreadPool(6);
executor.submit(MutGb);
executor.submit(MutRdm);
executor.submit(CrossOp);
executor.submit(CrossOp2);
executor.submit(CrossOpg);
executor.submit(MbsR);

start a thread which terminates the process after a specified time

I am executing a program for a network where i have a certain number of tasks execution in loop, it works fine but when there a any flaws occurs due to network problem it got stuck in one of any task. so i want to create a thread which start at the time when control goes in to loop and after some delay it terminate it self with continuing the process.
for example-
for ( /*itearting condition */)
{
//thread start with specified time.
task1;
task2;
task3;
//if any execution delay occur then wait till specified time and then
//continue.
}
Please give me some clue regarding this, a snippets can help me a lot as i need to fix it shortly.
A thread can only be terminated with its cooperation (assuming you want to save the process). With the thread's cooperation, you can terminate it with any termination mechanism it supports. Without its cooperation, it cannot be done. The usual way to do it is to design the thread to sanely handle being interrupted. Then you can have another thread interrupt it if too much time passes.
I think you may need something like this:
import java.util.Date;
public class ThreadTimeTest {
public static void taskMethod(String taskName) {
// Sleeps for a Random amount of time, between 0 to 10 seconds
System.out.println("Starting Task: " + taskName);
try {
int random = (int)(Math.random()*10);
System.out.println("Task Completion Time: " + random + " secs");
Thread.sleep(random * 1000);
System.out.println("Task Complete");
} catch(InterruptedException ex) {
System.out.println("Thread Interrupted due to Time out");
}
}
public static void main(String[] arr) {
for(int i = 1; i <= 10; i++) {
String task = "Task " + i;
final Thread mainThread = Thread.currentThread();
Thread interruptThread = new Thread() {
public void run() {
long startTime = new Date().getTime();
try {
while(!isInterrupted()) {
long now = new Date().getTime();
if(now - startTime > 5000) {
//Its more than 5 secs
mainThread.interrupt();
break;
} else
Thread.sleep(1000);
}
} catch(InterruptedException ex) {}
}
};
interruptThread.start();
taskMethod(task);
interruptThread.interrupt();
}
}
}

Synchronization of many objects and counter

I know it lot of people have problems with this topic and you might be bored, but I try to understand it since few days and still don't know how it works:(. I have a counter object, and other objects of another class (in the future more then one class). Now each object should respond for counters execution. One count - one step of each objects run method. That's my code:
public class Th {
private final static Object lock1 = new Object();
////////////////////////////////////////////////////////////////////////////////
private class Stop implements Runnable {
private int count, id;
public Stop(int id) {
this.count = 0;
this.id = id;
}
#Override public void run() {
synchronized(lock1){
while (count < 20) {
try {
lock1.wait();
}
catch (InterruptedException exception) {
System.out.println("Error!");
}
System.out.println(count + " stop " + id);
this.count++;
// try {
// Thread.sleep(360);
// }
// catch (InterruptedException exception) {
// System.out.println("Error!");
// }
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
private class Counter implements Runnable {
private int count;
public Counter() {
this.count = 0;
}
#Override public void run() {
synchronized(lock1){
while (count<15) {
lock1.notifyAll();
System.out.println(count + " counter");
this.count++;
// try {
// Thread.sleep(360);
// }
// catch (InterruptedException exception) {
// System.out.println("Error!");
// }
}
}
}
}
public void test() {
Stop s1 = new Stop(1);
Stop s2 = new Stop(2);
Stop s3 = new Stop(3);
Counter counter = new Counter();
(new Thread(s1)).start();
(new Thread(s2)).start();
(new Thread(counter)).start();
(new Thread(s3)).start();
}
}
and it returns me something like:
run:
0 counter
1 counter
2 counter
3 counter
4 counter
5 counter
6 counter
7 counter
8 counter
9 counter
10 counter
11 counter
12 counter
13 counter
14 counter
0 stop 1
what I need is:
0 counter
0 stop 0
0 stop 1
0 stop 2
1 counter
1 stop 0
1 stop 1
1 stop 2
2 counter
2 stop 0
2 stop 1
2 stop 2
3 counter
...
The entire loop of the Counter thread is synchronizd on lock1. This means that although you call notifyAll in this loop, other threads can't reacquire the lock until the complete loop has ended in the Counter thread.
Make each iteration of the loop synchronized, instead of synchronizing outside of the loop.
Note that this won't be sufficient, though, because the Counter thread might reacquire the lock before all the Stop threads have reacquired it. You'll need to make the Counter thread wait on another condition, and make it restart when all the Stop threads have displayed the count.
You should investigate higher-level abstractions, like CyclicBarrier and CountDownLatch.
First, the best way to solve this is to use the higher level synchronization classes, as JB Nizet says.
But if you want to do it "the hard way" as a learning exercise, you need to recognize that this problem requires the Counter and Stop threads to wait for specific "events".
The Stop threads need to wait until the Counter thread tells them to advance to the next stop.
The Counter thread needs to wait until all Stop threads have advanced and stopped.
One problem with your current implementation is that the Counter thread has nothing to tell it when all of the Stop threads have advanced and stopped. Instead, it assumes that when it sees a notify event that it is ok to issue the next count.

java- timing the execution of a block of code

hi
i want a block of code(certain lines of a function) that will run for a stipulated amount of time (say x milliseconds).Is is possible to do this in java?
1st approach:
long startTime = System.nanoTime();
while(System.nanoTime() - startTime < MAX_TIME_IN_NANOSECONDS){
// your code ...
}
2nd approach
Start your code in thread.
Sleep main thread for as long as you need.
Kill (stop, interrupt) your thread.
either use an exit condition based on current timestamp, or create a separate thread and kill it after a specified timeout.
Run your method in a separate thread, but passing it to an Executor. You can then use the Future to wait a certain period of time for the the thread to complete. If it doesn't complete, you will get a TimeoutException and you can then cancel the thread. Cancelling the thread causes the thread to be interrupted. So your code will have to periodically check the thread's interrupted status and exit if necessary.
For example:
ExecutorService exec = Executors.newSingleThreadExecutor();
Future<Integer> future = exec.submit(new Callable<Integer>(){
#Override
public Integer call() throws Exception {
//do some stuff
//periodically check if this thread has been interrupted
if (Thread.currentThread().isInterrupted()) {
return -1;
}
//do some more stuff
//check if interrupted
if (Thread.currentThread().isInterrupted()) {
return -1;
}
//... and so on
return 0;
}
});
exec.shutdown();
try {
//wait 5 seconds for the task to complete.
future.get(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
//the task did not complete in 5 seconds
e.printStackTrace();
System.out.println("CANCELLING");
//cancel it
future.cancel(true); //sends interrupt
}
You could use Calendar:
timeInMilis = Calendar.getInstance().getTimeInMillis();
while(Calendar.getInstance().getTimeInMilis() - timeInMilis < MAX_TIME_IN_MILIS){
// Execute block
}
Check the time using System.currentTimeMillis() and exit your loop after the time has passed.
long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
// do your stuff
}
If you need to sleep inside the thread for some reason, adjust your sleep time to end at the end time.
long timeLeft = endTime - System.currentTimeMillis();
if (sleepAmount > timeLeft)
sleepAmount = timeLeft;
Thread.sleep(sleepAmount);
If you're going to use the wait() and notify() method, then use the calculated timeLeft as the argument to wait() to ensure the maximum wait time. Once that wait time hits, the method will return and the loop will break.
long timeLeft = endTime - System.currentTimeMillis();
if (timeLeft > 0)
this.wait(timeLeft);
If you're running multiple steps inside the loop which can take a long time, you should add additional checks between steps, if you want the process to break between steps, to exit the loop if the designated time has passed. This is a design decision. When the timer expires, do you want the task to finish up the step it's working on and then exit? It's up to you how to code it based on the desired result.
long endTime = System.currentTimeMillis() + ClassName.EXECUTION_TIME_MS;
while (System.currentTimeMillis() < endTime) {
this.doFirstLongThing();
if (System.currentTimeMillis() >= endTime) break;
this.doSecondLongThing();
if (System.currentTimeMillis() >= endTime) break;
this.doThirdLongThing();
}

Categories