stopping application after some time - java

I want to do some calculation, but if they took too much time(say 10 sec), I want to stop it and show current best result.
Is it ready way to do it in Java? I don't want to write time checking in every function.

Use Timer as suggested or go for multiple threads. In your main program, another thread with the calculation is started. The main thread sleeps via Thread.sleep and terminates the calculation after the timeout.
main thread +-------+---sleeping---termination----+
| |
another thread +---calculation---+

You could make a separate thread that you can start at the beginning of your calculation thread, and after 10 seconds with the Timer.sleep(int) method, set a boolean value to true. Then in the calculation thread, if(finished) break;

Have another thread with a loop that increments a value every second, and then exits at 10 seconds.
public class counter extends Thread, implements Runnable{
public void run()
{
for(int index=0; index<10; index++)//Waits ten seconds
{
this.sleep(1000);//ms
}
System.exit(0);//Closes the application
}
The main Thread can still execute, though. To cancel the shutdown I suppose you could have a volatile boolean that gets set to true if input was recieved in time.

Related

Threads in Java with while loop

We have 2 Threads in Java:
Thread 1:
…
public void run()
{
while (Share.COUNTER<8)
Share.COUNTER++;
}
…
Thread 2:
…
public void run()
{
while (Share.COUNTER>-7)
Share.COUNTER--;
}
…
The question is: Which thread is going to be terminated by the while loop at first?
The second question is:
Is there a guarantee that the threads will terminate the run methods?
Could you help me answering this questions since threads in Java is new to me.
Which thread is going to be terminated by the while loop at first?
Most likely which ever thread starts first. A thread takes time to start and one thread could count to one million in the time it takes the other one to start.
Is there a guarantee that the threads will terminate the run methods?
Both threads should terminate almost immediately.
can't thread 1 run while thread 2 is running, too?
They can but they won't start at precisely the same time and since counting to 8 takes almost no time at all (it could be a fraction of a microsecond), it will terminate pretty quickly.

Thread run() method execution different on Run and Debug in eclipse

For the below program different outputs are coming when running and debugging on eclipse.
public class MyClass implements Runnable {
public static void main (String[] args) throws Exception {
Thread t = new Thread(new MyClass());
t.start();
System.out.print("Started");
t.join();
System.out.print("Complete");
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.print(i);
}
}
}
When running this as java application the OUTPUT is
Started0123Complete
When checking in Debug Mode OUTPUT is
0123StartedComplete
Can someone help on this? is it because of two threads? main thread and the thread which starts with t.start().If yes then why main thread execution is taking more priority to complete first?
Thanks
The order in which the string "Started" and the integers are printed out is undefined by definition. After you call start, there is no guarantee that the code in the run method will be executed before or after any other statement that appears before the call to join. This is the nature of multithreaded applications.
The fact that you see a certain output in debug mode vs run mode is probably purely accidental and might change if you run your code many times or on different platforms/versions of the JVM. If you need deterministic order in this case, the only way you can achieve it is to print a string before calling start or introduce some other sort of semaphore to force the thread to wait for the main thread or viceversa.
It's coincidence. You can't control the thread scheduler.
However, in a debug environment, the debugger plugs into your code to inspect values and execution. This inspection increases the amount of work done per thread time slice.
For example, in a regular run, the main thread may only need 1 time slice to create the new thread object, start it, and print the Started message. Then a context switch would occur and the second thread would get a chance to work. In a debug run, the main thread would only have enough time to create the new thread object and start the corresponding thread. Then the context switch would occur and the other thread would do its thing.
It is not related to being in debug mode or not.
There is no guarantee of when this gets executed
System.out.print("Started"); //this is in the main thread
compared to
for (int i = 0; i < 4; i++) { // this is in the started thread
System.out.print(i);
}
It can even be
01Started23Complete
Yes, Its because of 2 threads But the output is unpredictable.
No, the main thread doesn't get high priority because its MAIN.
you can't say any particular interleaved execution in multithreads.
In Debug, my guess is you put a break point for main thread so it waits and in the mean time the other thread might have executed.
In both (Run / Debug) the mode output will be
Started0123Complete
You are seeing result 0123StartedComplete, because you must be having debug point inside main thread code, that’s why.
If you want to understand better, then move the run() method to inside MyClass and put debugger point inside run method now you will see it is printing as Started0123Complete.
Internally, Main Thread is creating subthread “t” and when t.start() is being called it is waiting to capture the monitor for thread execution (i.e. run()) and when you are adding debug statement in main thread, sub-thread is entering into monitor and run method is executing and once it completed, main thread is starting again.

Is it always necessary to wait for every thread to terminate before actually closing main one?

Suppose I have a main thread and a normal thread, whose execution lasts more than the former one.
Something like it:
public class Test{
private int count;
public void doTest(){
(new MyThread()).start();
}
public static void main(String[] args){
Test t = new Test();
t.doTest();
}
private class MyThread extends Thread{
public void run(){
while(count < 100){
count++;
..wait some secs ...
}
}
}
}
Is it wrong to just leave code like that? Or would it be more correct perform a join() on the thread so to make sure that it correctly ends?
This is one of the question, for which the answer is: It depends.
There is no technical reason to have the main thread running till all other threads are terminated. In fact, you can handle the main thread like every other thread. As I recommend to not have a thread keeping alive when it already has done its business and can be terminated, a main thread that only starts other threads should simply terminate after starting the others.
Remind: The JVM itself is not terminated when the main thread terminates. The JVM will only terminate when all non-daemon threads are terminated.
I think you maybe also looking for a scenario when it is "not okay to exit before all thread exit" / "wait till all threads exit, and then exit the main program".
While developing games, at least in java , we do need to take care that all thread exit before the main program exits . If you ask why, then let me explain you with an example which should clear things for you.
If there are 3 threads, controlling different aspects of game.
Thread 1: Controls the game background sounds/music/audio.
Thread 2: Controls the Artificial intelligence .
Thread 3: Controls the Graphics Rendering .
And consider this scenario, if the user closes his game, and if the threads are not waited upon before closing then there can a be case where in the main window of the game is closed i.e. Thread 2, Thread 3 but not Thread 1. So you will have the game music still playing even when the game window is not seen. That would be pretty embarrassing for any game developer.
It is perfectly fine.
No join or System.exit necessary.
Each thread lives its own life. As long as at least one thread is running, the program keeps running.
The JVM will automatically exit as soon as there are no more non-daemon threads running.
If you don't call setDaemon(true) before launching the thread, the JVM will automatically exit when your Thread is done. No need to call join() on the Thread, if all you want is for the process to end as soon as your thread ends.
Unless the thread runs in an endless loop, it will end at some time, the question is whether you want to wait for the termination of that thread or not? You may want to wait If the further processing depends on the result of thread you have started. If that thread just does some work and ends then just leave it.

Android/Java thread sleeping

Alongside the implicit User Interface thread, i have made two threads (runnables), both having a while loop inside them in which i periodically check for updates inside a message queue which I've implemented.
The problem at first was that the two while loops were infinite, and they changed so quickly and so much that they used up almost all the CPU of the device.
So i thought about making the while loops sleep for about 100 milisec after each cycle, to let the other threads do their work, but i came across another issue:
NOW, the problem is that the threads sleep for 100 milliseconds, but they don't let the UI thread work during that time :( And what this does is make the UI laggy. When i drag something on the screen it lags a bit.
So what i want to do is make these threads (these while loops) check the message queue flag every 100 miliseconds, but during those 100 miliseconds i want to let the UI thread run. How can this be accomplished?
EDIT 1
I found the yield method, which stops the running of the current thread, but when do i call this? I would need to call the sleep thread and at the same time make it yield somehow ... ??
EDIT 2
The two classes are singletons, and i start them from the first Activity of the application, so when the app starts (the UI thread)
//Obtain object of singleton classes
ControllerSingleton controller = ControllerSingleton.getControllerSingleton();
OpponentSingleton opponent = OpponentSingleton.getOpponentSingleton();
//Start threads
/*--------CONTROLLER----------*/
Thread t;
t = new Thread( controller );
t.setName("ControllerThread");
Log.i("Remy","Starting Controller thread...");
t.start();
/*--------OPPONENTS----------*/
t = new Thread( opponent );
t.setName("OpponentThread");
Log.i("Remy","Starting Opponent thread...");
t.start();
And inside each run() i have the next code:
public void run()
{
while( true )
{
//Check if any messages in the queue
if ( queueEmpty() == false )
{
//Do something ...
}
/*HERE IS WHERE I WOULD LIKE TO TELL THE THREAD TO STOP AND WAIT FOR 100 ms*/
}
}
I think that the thing you need to use is Handler. You might want to see this tutorial for example.

Is my way of doing threads in Android correct?

I'm writing a live wallpaper, and I'm forking off two separate threads in my main wallpaper service. One updates, and the other draws. I was under the impression that once you call thread.start(), it took care of everything for you, but after some trial and error, it seems that if I want my update and draw threads to keep running, I have to manually keep calling their run() methods? In other words, instead of calling start() on both threads and forgetting, I have to manually set up a delayed handler event that calls thread.run() on both the update and draw threads every 16 milliseconds. Is this the correct way of having a long running thread?
Also, to kill threads, I'm just setting them to be daemons, then nulling them out. Is this method ok? Most examples I see use some sort of join() / interrupt() in a while loop...I don't understand that one...
No
No
For #1, I believe your threads are terminating. Once the run() method is left, the thread is considered terminated. If you want the thread to run "forever", you need to repeat your actions.
For #2, the thread will continue running even if you lose all references to it. I would suggest a signal or condition to the worker thread, followed by a join() in the main thread.
Like Yann said, if you keep having to restart your thread(s), it means you are probably not looping correctly.
Say your wallpaper just has a ball moving around the screen, this would be a sample run() method:
boolean isAnimating;
public void run() {
isAnimating = true;
while(isAnimating) {
moveBall();
isAnimating = isWallpaperVisible(); // or whatever conditions apply to not keep animating
}
}
This way your run method will keep running indefinitely.

Categories