how to check if thread is running or waiting in android - java

i have a thread that i want to know when the wait method is running. and when the thread is running
here is my code:
runnableClass rc = new runnableClass();
Object PauseTHR = new Object();
boolean pause = false;
public class runnableClass implements Runnable {
#Override
public void run() {
while(true) {
// here is my code,after my code i want to wait thread
// so i call onpause();
onpause();
synchronized (PauseTHR) {
while(pause) {
Log.i("while loop", "it goes over me");
try {
PauseTHR.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void onpause() {
synchronized (PauseTHR) {
Log.i("synchronized", "it goes over me");
pause = true;
}
}
public void onresume() {
synchronized (PauseTHR) {
pause = false;
PauseTHR.notifyAll();
}
}
}
i set my boolean(pause) variable as global but when i check
if(pause == true)
rc.onresume();
out of my Runnable class it seems doesn't work and my condition works
how can i check when my thread is waiting and when my thread is runnig ??

check your thread is alive or not by this code:
thread1.isAlive()
it returns a boolean. Returns true if the receiver has already been started and still runs code (hasn't died yet). Returns false either if the receiver hasn't been started yet or if it has already started and run to completion and died.

Use Thread.getState() method
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html
A thread can be in one of the following states:
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED

Related

Pausing/sleeping threads in java [duplicate]

I state that I read about thread, but I've never used.
So I ask to you :)
I have two thread: A and B,
where A manages the GUI, and B manages the logic.
I would start with A.
Then when A draw the GUI, I would pause it, to wait B that reach a point X into run method.
And when B reach the X point into run method, I pause B, and resume A.
A and B share some variable to manage the GUI, and the logic...
Can I do it? if yes, how? :)
Using wait() and notify() methods:
wait() - Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
notify() - Wakes up a single thread that is waiting on this object's monitor.
You can block threads using the wait and notify methods of the Object class, but it can be tricky to get right. Here's an example inside an infinite loop in a Runnable:
public class Example implements Runnable {
private volatile boolean running = true;
private volatile boolean paused = false;
private final Object pauseLock = new Object();
#Override
public void run() {
while (running) {
synchronized (pauseLock) {
if (!running) { // may have changed while waiting to
// synchronize on pauseLock
break;
}
if (paused) {
try {
pauseLock.wait(); // will cause this Thread to block until
// another thread calls pauseLock.notifyAll()
// Note that calling wait() will
// relinquish the synchronized lock that this
// thread holds on pauseLock so another thread
// can acquire the lock to call notifyAll()
// (link with explanation below this code)
} catch (InterruptedException ex) {
break;
}
if (!running) { // running might have changed since we paused
break;
}
}
}
// Your code here
}
}
public void stop() {
running = false;
// you might also want to interrupt() the Thread that is
// running this Runnable, too, or perhaps call:
resume();
// to unblock
}
public void pause() {
// you may want to throw an IllegalStateException if !running
paused = true;
}
public void resume() {
synchronized (pauseLock) {
paused = false;
pauseLock.notifyAll(); // Unblocks thread
}
}
};
(For more information on why we need to synchronize as illustrated above whilst calling wait and notifyAll, see the Java tutorial on the subject.)
If another Thread calls this Runnable's pause() method, then the Thread running the runnable will block when it gets to the top of the while loop.
Note that it is not possible to pause a thread at any arbitrary point. You need the Thread to periodically check whether it should pause and block itself if so.
I would expect that you don't need to pause the GUI thread. The operating system will take care of that, and it needs to be ready to respond in case the user does something.
One other thought is to make sure the shared variables are properly synchronized between the two threads. I tried answering a question relating to that recently, see here.
you can use a CountDownLatch. When Thread A has to wait for Thread B will call countDownLatchInstance.await(); When B reach the X point will invoke countDownLatchInstance.countDown(); allowing A to continue its execution flow.
When you say
A manages the GUI
I hope you do not refer to the UI/Main Thread
,
public class Mutex {
private final AtomicBoolean lock;
private final Object mutex;
public Mutex(boolean lock) {
this.lock = new AtomicBoolean(lock);
this.mutex = new Object();
}
public void step() {
if (lock.get()) synchronized(mutex) {
try {
mutex.wait();
} catch (InterruptedException ex) {}
}
}
public void lock() {
lock.set(true);
}
public void unlock() {
lock.set(false);
synchronized(mutex) {
mutex.notify();
}
}
}
Just add Mutex object to your thread and make getter.
public class MyThread extends Thread {
private final Mutex mutex;
public MyThread() {
this.mutex = new Mutex(false);
}
public Mutex getMutex() {
return this.mutex;
}
#Override
public void run() {
while (!isInterrupted()) {
mutex.step();
// do your code
}
}
}
If you want to pause the thread just call
myThread.getMutex().lock();
If you want to resume the thread just call
myThread.getMutex().unlock();
That's the way I got thread's wait and notify working for me:
public class Main {
public static void main(String[] args) {
final Object lock = new Object();
MyThread t = new MyThread();
t.lock = lock;
t.run();
while (true) {
try {
synchronized (lock) {
lock.wait();
}
System.out.println("hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MyThread extends Thread {
Object lock;
#Override
public void run() {
JFrame fr = new JFrame("Anothing");
JButton btn = new JButton("Next");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
synchronized (lock) {
lock.notify();
}
}
});
fr.setLayout(new FlowLayout());
fr.add(btn);
fr.setSize(400, 400);
fr.setVisible(true);
}
}
Then, whenever I press the button, the other thread wakes up, executes one round and waits for a new clicking.
The java primitive to suspend and resume a thread is deprecated. See this to figure how you can achieve best what you need - http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Check how you can do the equivalent of suspend & resume
What should I use instead of Thread.suspend and Thread.resume?
As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.
Example code is given in the same answer to help you achieve this.

How to stop execution of method called from run() method of thread

Here is my Thread:-
Thread t=new Thread(){
public void run(){
downloadFile();
}
}
t.start();
public static void main(){
t.interrupt();
}
Here downloadFile() is long running method (downloading file from server)
The issue is , even though t.interrupt() is called downloadFile() method still keeps running which is not expected . I want downloadFile() method to terminate immediately as soon as the thread is interrupted. How should i achieve it ?
Thanks.
EDIT1:
Here is downloadFile() skeleton which calls the rest API to fetch file:
void downloadFile(){
String url="https//:fileserver/getFile"
//code to getFile method
}
Your Runnable needs to store an AtomicBoolean flag to say whether it has been interrupted or not.
The interrupt method should just set the flag to true.
The downloadFile() method needs to check the flag inside the download loop and abort the download if it is set.
Something like this is the only clean way to implement it as only downloadFile knows how to safely and cleanly interrupt itself, closing sockets etc.
You need some flag to inform a thread about termination:
public class FileDownloader implements Runnable {
private volatile boolean running = true;
public void terminate() {
running = false;
}
#Override
public void run() {
while (running) {
try {
downloadFile();
} catch (InterruptedException e) {
running = false;
}
}
}
}
in main:
FileDownloader fileDownloaderRunnable = new FileDownloader();
Thread thread = new Thread(fileDownloaderRunnable);
thread.start();
//terminating thread
fileDownloaderRunnable.terminate();
thread.join();

How pause and then resume a thread?

I state that I read about thread, but I've never used.
So I ask to you :)
I have two thread: A and B,
where A manages the GUI, and B manages the logic.
I would start with A.
Then when A draw the GUI, I would pause it, to wait B that reach a point X into run method.
And when B reach the X point into run method, I pause B, and resume A.
A and B share some variable to manage the GUI, and the logic...
Can I do it? if yes, how? :)
Using wait() and notify() methods:
wait() - Causes the current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
notify() - Wakes up a single thread that is waiting on this object's monitor.
You can block threads using the wait and notify methods of the Object class, but it can be tricky to get right. Here's an example inside an infinite loop in a Runnable:
public class Example implements Runnable {
private volatile boolean running = true;
private volatile boolean paused = false;
private final Object pauseLock = new Object();
#Override
public void run() {
while (running) {
synchronized (pauseLock) {
if (!running) { // may have changed while waiting to
// synchronize on pauseLock
break;
}
if (paused) {
try {
pauseLock.wait(); // will cause this Thread to block until
// another thread calls pauseLock.notifyAll()
// Note that calling wait() will
// relinquish the synchronized lock that this
// thread holds on pauseLock so another thread
// can acquire the lock to call notifyAll()
// (link with explanation below this code)
} catch (InterruptedException ex) {
break;
}
if (!running) { // running might have changed since we paused
break;
}
}
}
// Your code here
}
}
public void stop() {
running = false;
// you might also want to interrupt() the Thread that is
// running this Runnable, too, or perhaps call:
resume();
// to unblock
}
public void pause() {
// you may want to throw an IllegalStateException if !running
paused = true;
}
public void resume() {
synchronized (pauseLock) {
paused = false;
pauseLock.notifyAll(); // Unblocks thread
}
}
};
(For more information on why we need to synchronize as illustrated above whilst calling wait and notifyAll, see the Java tutorial on the subject.)
If another Thread calls this Runnable's pause() method, then the Thread running the runnable will block when it gets to the top of the while loop.
Note that it is not possible to pause a thread at any arbitrary point. You need the Thread to periodically check whether it should pause and block itself if so.
I would expect that you don't need to pause the GUI thread. The operating system will take care of that, and it needs to be ready to respond in case the user does something.
One other thought is to make sure the shared variables are properly synchronized between the two threads. I tried answering a question relating to that recently, see here.
you can use a CountDownLatch. When Thread A has to wait for Thread B will call countDownLatchInstance.await(); When B reach the X point will invoke countDownLatchInstance.countDown(); allowing A to continue its execution flow.
When you say
A manages the GUI
I hope you do not refer to the UI/Main Thread
,
public class Mutex {
private final AtomicBoolean lock;
private final Object mutex;
public Mutex(boolean lock) {
this.lock = new AtomicBoolean(lock);
this.mutex = new Object();
}
public void step() {
if (lock.get()) synchronized(mutex) {
try {
mutex.wait();
} catch (InterruptedException ex) {}
}
}
public void lock() {
lock.set(true);
}
public void unlock() {
lock.set(false);
synchronized(mutex) {
mutex.notify();
}
}
}
Just add Mutex object to your thread and make getter.
public class MyThread extends Thread {
private final Mutex mutex;
public MyThread() {
this.mutex = new Mutex(false);
}
public Mutex getMutex() {
return this.mutex;
}
#Override
public void run() {
while (!isInterrupted()) {
mutex.step();
// do your code
}
}
}
If you want to pause the thread just call
myThread.getMutex().lock();
If you want to resume the thread just call
myThread.getMutex().unlock();
That's the way I got thread's wait and notify working for me:
public class Main {
public static void main(String[] args) {
final Object lock = new Object();
MyThread t = new MyThread();
t.lock = lock;
t.run();
while (true) {
try {
synchronized (lock) {
lock.wait();
}
System.out.println("hello");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MyThread extends Thread {
Object lock;
#Override
public void run() {
JFrame fr = new JFrame("Anothing");
JButton btn = new JButton("Next");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
synchronized (lock) {
lock.notify();
}
}
});
fr.setLayout(new FlowLayout());
fr.add(btn);
fr.setSize(400, 400);
fr.setVisible(true);
}
}
Then, whenever I press the button, the other thread wakes up, executes one round and waits for a new clicking.
The java primitive to suspend and resume a thread is deprecated. See this to figure how you can achieve best what you need - http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Check how you can do the equivalent of suspend & resume
What should I use instead of Thread.suspend and Thread.resume?
As with Thread.stop, the prudent approach is to have the "target thread" poll a variable indicating the desired state of the thread (active or suspended). When the desired state is suspended, the thread waits using Object.wait. When the thread is resumed, the target thread is notified using Object.notify.
Example code is given in the same answer to help you achieve this.

Returning/Stopping the execution of a function on a keypress in Java

I have a certain function in my program that I want to stop on the press of a key. I have a native keyboard hook set up for that purpose. Right now, I call System.exit(0) when that key is detected. However, I don't want to exit the program, just stop that operation and return to where it was called. An example is given below.
public class Main {
public static void main(String[] args) {
System.out.println("Calling function that can be stopped with CTRL+C");
foo(); // Should return when CTRL+C is pressed
System.out.println("Function has returned");
}
}
I've tried putting the call to foo() in a thread so I could call Thread.interrupt() but I want the function call to be blocking, not non-blocking. Also there are blocking IO calls in foo() so I'd rather not deal with interrupts unless it's necessary, because I'd have to deal with ClosedByInterruptException exceptions and that has caused problems before.
Also the body of foo() is very long and has many function calls inside it, so writing if (stop == true) return; in the function is not an option.
Is there a better way to do this than making a blocking thread? If so, how? If not, how would I make a blocking thread?
How about this?
// Create and start the thread
MyThread thread = new MyThread();
thread.start();
while (true) {
// Do work
// Pause the thread
synchronized (thread) {
thread.pleaseWait = true;
}
// Do work
// Resume the thread
synchronized (thread) {
thread.pleaseWait = false;
thread.notify();
}
// Do work
}
class MyThread extends Thread {
boolean pleaseWait = false;
// This method is called when the thread runs
public void run() {
while (true) {
// Do work
// Check if should wait
synchronized (this) {
while (pleaseWait) {
try {
wait();
} catch (Exception e) {
}
}
}
// Do work
}
}
}
(taken from http://www.exampledepot.com/egs/java.lang/PauseThread.html not my own work)

how to destroy a thread , pause/suspend a thread , resume/runAgain a thread?

Hey guys
I am using runnable outside the oncreate in my android application where i have used thread to setprogress of ProgressBar. What i dont know is how to stop/destry the thread when stop button is pressed since thread.stop is not a method and how to resume from that , how to even destroy the thread.
I know i have to make some methods and members in runnable but i dont exactly know what??
Thread.stop() is no longer used since it was considered dangerous: http://download.oracle.com/javase/1.4.2/docs/guide/misc/threadPrimitiveDeprecation.html.
You must let the thread come naturally to an end as a result of a variable change. The link also gives some advice about how to achieve this.
public class MyThread extends Thread {
private boolean threadDone = false;
public void done() {
threadDone = true;
}
public void run() {
while (!threadDone) {
// work here
// modify common data
}
}
}
Warning: make sure you either use a guarded block in the looping code, a method that blocks itself, or a Thread.sleep(..). Thread.sleep is the most primitive of these if you don't understand guarded blocks, but it will work. You could also wait forever and use the interrupt mechanism to cancel the thread which is thrown as InterruptedException in the try-catch block when you use a wait or sleep. For this, use !Thread.currentThread().isInterrupted() as the loop guard condition, then use your Thread object and call thread.interrupt().
To control a Java thread, you should add methods to the object that can be called by other objects which set variables read by your run() method. You don't give much information on exactly what you're doing, but here's a possible pattern:
public class ProgressBarUpdater implements Runnable{
private volatile boolean paused = false;
private volatile boolean finished = false;
/* other fields, constructor etc. */
public void run(){
while(!finished){
updateProgressBar();
while(paused && !finished){
try{
Thread.sleep(1000); //Busy wait - should really use wait/notify, but that's another lesson
}
catch(InterruptedException e){
}
}
}
}
public synchronized void pauseProgressBar(){
paused = true;
}
public synchronized void unPauseProgressBar(){
paused = false;
//call notify() here when you switch to wait/notify.
}
public void stopProgressBar(){
finished = true;
//call notify() here too.
}
}
You will probably want to use more robust synchronisation around the control variables, and, as mentioned in the comments, wait/notify rather than a busy wait.
Use as so:
ProgressBarUpdater pbu = new ProgressBarUpdater();
Thread t = new Thread(pbu);
t.start();
Thread.sleep(10000); //let the progress bar run for ten seconds.
pbu.pauseProgressBar();
Thread.sleep(10000); //pause it for ten seconds.
pbu.unPauseProgressBar();
Thread.sleep(10000); //restart for another ten seconds.
pbu.stopProgressBar(); //stop progress bar.
You have a few options and they depend on how you define the various states of your thread.
A thread is effectively stoped when it exits the run() method.
To "pause" and "resume" a thread's execution you can can use wait() and notify().
To illustrate this, here's a quick example:
class MyThread implements Runnable {
private boolean keepRunning = false;
private boolean isPaused = false;
public void run() {
keepRunning = true;
try {
while (keepRunning) {
// do stuff here
if (isPaused) {
synchronized (this) {
// wait for resume() to be called
wait();
isPaused = false;
}
}
}
} catch (Exception ex) {
// do stuff
}
}
// note that as-is this won't do anything to a paused thread until
// it is resumed.
public void stop() {
keepRunning = false;
}
public void pause() {
isPaused = true;
}
public synchronized void resume() {
// notify anybody waiting on "this"
notify();
}
}
Have the other thread check a boolean flag (isCancelled, or something like that) periodically. Initially is is false.
From your stop button code, set this value to true.
When your thread next checks the flag and finds it to be true, the thread should kill itself.

Categories

Resources