Android isInterrupted() returns false after interrupting Thread - android

I have a thread waiting to be notified or to time out
while (!isInterrupted()) {
try {
if (!semaphore.tryAcquire(timeout, TimeUnit.MILLISECONDS)) {
Context context = getContext();
// this is where i do my stuff
semaphore.aquire();
}
} catch (InterruptedException ignored) {
ignored.printStackTrace();
}
}
Before i quit my app i call Thread#interrupt() on this thread. Now i debugged the interrupt seemed to be executed fine since the InterruptedException was thrown and the waiting has been canceled.
But for some reason isInterrupted() still returns true after this and the while loop keeps on running.
Why is that?

you can use a boolean in your while loop condition term because when you send the interrupt command, it won't stop the thread and the thread itself decide when to stop itself

Related

How to pause and resume a Thread?

I have a thread:
class SomeRunnable implements Runnable {
#Override
public void run() {
while (true) {
//some code...
try {
Thread.sleep(33);
} catch (InterruptedException e) {
return;
}
}
}
}
which I start using:
someThread = new Thread(new SomeRunnable());
someThread.setName("SomeThread");
someThread.start();
If I want to stop the thread I simply interrupt it:
someThreat.interrupt();
How can I later resume the thread?
Thank you!
You can use wait() and notify() method.
wait()
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
notify()
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. A thread waits on an object's monitor by calling one of the wait methods.

How to stop this thread?

I implemented this class in my android code
I made the below change in the run method(replaced "true"):
#Override
public void run() {
while (!isInterrupted()) {
try {
// A blocking operation. Initiate a ChatManager instance when
// there is a new connection
pool.execute(new ChatManager(socket.accept(), handler));
Log.d(TAG, "Launching the I/O handler");
} catch (IOException e) {
try {
if (socket != null && !socket.isClosed())
socket.close();
} catch (IOException ioe) {
}
e.printStackTrace();
pool.shutdownNow();
break;
}
}
}
I want to stop this thread before I close the app. So I implemented threadName.interrupt(); method. But this doesn't interrupt the thread.
I am actually confused with the usage of thread pool executor. So I am not sure how to do this efficiently. How can I implement interrupting this thread? When interrupt method is called, I want to close the socket, shutdown the pool and stop the thread.
Thread thread = new Thread () {
boolean isRunning = true;
public void stopThread() {
isRunning = false;
}
#Override
public void run() {
while (isRunning) {
try {
// A blocking operation. Initiate a ChatManager instance when
// there is a new connection
pool.execute(new ChatManager(socket.accept(), handler));
Log.d(TAG, "Launching the I/O handler");
} catch (IOException e) {
try {
if (socket != null && !socket.isClosed())
socket.close();
} catch (IOException ioe) {
}
e.printStackTrace();
pool.shutdownNow();
break;
}
}
}
};
thread.start();
Try this code. and call thread.stopThread() whenever you want the thread to stop.
if you want close an Android thread, you can set a variable to control run(),because run() is end, the thread will be closed.
The code is something like:
final boolean istrue=true;
new Thread(new Runnable() {
#Override
public void run() {
while (istrue){
//TODO your work
}
}
}).start();
}
If you want to close the thread, you only set istrue=false
Just call shutDownNow to close the pool and try interrupt all the threads inside it. You can check the difference in this post:
shutdown() will just tell the executor service that it can't accept new tasks, but the already submitted tasks continue to run
shutdownNow() will do the same AND will try to cancel the already submitted tasks by interrupting the relevant threads. Note that if
your tasks ignore the interruption, shutdownNow will behave exactly
the same way as shutdown.
If you want to interrupt or cancel an specific thread. I suggest you to use submit with Callables, With this, you will me able to work with your Future object, then if want to cancel a task you've given an executor service, you can call cancel(true) on its associated Future. When your task detects an interrupt request, it should preserve the interrupted status by calling Thread.currentThread().interrupt().

Android- Thread.join() causes Application to hang

I have a thread which handles my game loop, when i call .join() on this thread the application stops responding.
I've been trying to fix a problem where the programs never get to the code, I.E the thread never ends.
System.out.println("YAY");
My Thread for the Game Loop:
This thread successfully prints out "Game Ended" but never seems to finish.
Runnable startGameLoop = new Runnable() {//game loop
#Override
public void run() {
AiFactory ai = new AiFactory();
final Button play = (Button) findViewById(R.id.Play);
final Button pass = (Button) findViewById(R.id.Pass);
while(finish==false){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentPlayer = game.getPlayer();
if(currentPlayer.isPlayer()==false){
//System.out.println("passCount:" +game.getPasscount());
ai.decide(nextPlay, game.getPreviousPlayed(), currentPlayer, game.getPasscount() );
if(nextPlay.size()!=0){
runOnUiThread(new Runnable(){
public void run(){
changeArrow();
if(nextPlay.size() ==1){
play1Card();
}
else if(nextPlay.size()==2){
play2Card();
}
else if(nextPlay.size()==3){
play3Card();
}
else if(nextPlay.size()==5){
play5Card();
}
}
}
else{
game.addPassCount();
game.nextTurn();
runOnUiThread(new Runnable(){
public void run(){
changeArrow();
}
});
}
}
else if (currentPlayer.isPlayer()==true){
runOnUiThread(new Runnable(){
public void run(){
changeArrow();
play.setClickable(true);
if(game.getPasscount()==3){
pass.setClickable(false);
}
else{
pass.setClickable(true);
}
}
});
}
}
System.out.println("Game Ended");
}
};
Starting and joining the thread to the main thread:
Thread myThread = new Thread(startGameLoop);
myThread.start();
try {
myThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("YAY");
}
To my understanding .join() makes the current thread wait till the new thread has finished before carrying on.
Sorry if this is a stupid question, i'm quite new to threading.
When you call myThread.join() inside Activity.onCreate you block the main UI thread. Of course it looks like your application has stopped responding because the UI thread is the one responsible for redrawing UI. All your calls runOnUiThread never happen because your UI thread is busy waiting on your game loop.
Thread.join makes the current thread wait until the thread you call it on ends. It does not cause the thread you call it on to end. So if that thread is never ending (as you say at the top), calling join will make it hang forever.
If you want to actually end the thread, call cancel on it. But that requires your thread to occasionally call isCanceled() and exit its run function if it returns true.
mythread.join() does not ensure that your "mythread" is ended.
You need to place a notify() in your game loop.
...
...
System.out.println("Game Ended");
synchronized(mythread){
mythread.notify();
}
Basically, when you make a call to wait(), the code waits on the thread's monitor, and a call to notify() causes a thread waiting on the object's monitor to wake up.
Also, you can use notifyAll() to wake up all the waiting threads.
Alternatively, you can use timeout version of wait(), where the thread waits either till it gets notified or it times out.

Android Gameloop Thread.join() hangs application

Hey all i am implementing the gameloop found here: http://obviam.net/index.php/the-android-game-loop/
My question is why does having:
boolean retry = true;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// try again shutting down the thread
}
}
In my surfaceDestroyed() function of my game view hang the application?
thread.join() will BLOCK until the thread you're joining completes. If that thread never completes, that function will never release.
Because thread.join() blocks the calling thread until thread is done.

How to stop asynchronous thread after 5 seconds of running

Have to create thread and run it for 5 seconds, then I want to stop. How can I do that?
I can't do anything with time/milliseconds.
THX.
Threading in java is cooperative - you can not forcefully stop a thread. What you can do is signal it to stop (call interrupt() or raise a flag) and then the code willingly stops.
So:
Start running your worker thread. Inside it repeatedly (inside main working loop) check for isInterrupted() AND catch any InterruptedExceptions - exit the thread in this case.
Start a TimerTask to run for 5 sec, then call interrupt() on the worker thread.
Update: poster explained that he already has a working code, he just needs to run it asynchronously without blocking UI.
Solution: setup AsyncTask and run your code inside it's doInBackground() method.
Use the AsyncTask.cancel(true) method.
Sorry for not being clear here. Here is the example I have for synchronous thread.
My function listen() runs for 5 seconds then exits. Listen() is a UDP listener...
Problem I have with this code, it stops my main thread (my phone became unresponsive) until listed() finishes its 5 seconds run. I would like to use asynchronous thread to avoid my phone freezing up. When I said I can't do anything with time, I was trying to say that I can't put some sort of timer in listen() function then measure lapsed time then exit after 5 seconds. Can't do that.
Thread t = new Thread() {
public void run() {
try {
listen();
} catch (IOException e) {
Log.d(TAG, "IOException (Discovery) " + e);
e.printStackTrace();
}
synchronized (this) {
notifyAll();
}
}
};
synchronized (t) {
t.start();
try {
t.join(5000); // 5 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Categories

Resources