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();
}
}
Related
I am building an android application and I want an hour gap between two lines of code,
I use thread.sleep() method with 1800000 seconds but it makes my application irresponsive and closed the execution.
Any suggestions or help would be beneficial for me.
As #GaneshPokale suggested above, WorkManager is the best solution for your case.
Don't stop Main thread(=UI thread): Sleeping in the Main thread will stop your entire app, and it will lead you to ANR, which will make your app killed if your app is stopped more than 5 sec.
In this case, you need to create another thread. WorkManager is one of the solutions for such cases, which need to wait a long time. You can also use AlarmManager or some other ways.
Try running the code on a different thread:
class MyThread implements Runnable {
public void run() {
try {
Thread.sleep(1800000000);
} catch (InterruptedException err) {
//handle interruption
}
System.out.print("world!");
}
}
class Main {
public static void main(String[] args) {
System.out.print("Hello ");
Thread t = new Thread(new MyThread());
t.start();
}
}
This will allow the main thread to continue running tasks while the second one is waiting in the background.
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.
I wanted to execute a task inside a thread and wrote the following code:
Thread().run {
Log.i("TEST", "in thread")
Thread.sleep(5000);
transactionStatus = ApiFactory.getInstance().transactionService.abortTransaction()
synchronized(TestTransactionPayAbort.lock) {
TestTransactionPayAbort.lock.notify()
}
}
Log.i("TEST", "main")
synchronized(TestTransactionPayAbort.lock) {
TestTransactionPayAbort.lock.wait()
}
According to the debugger, before executing Thread().run{}, I'm inside thread 4.
After executing Thread.sleep(), the debugger tells me that thread 4 is sleeping whereas I was expecting to see that thread 5 is sleeping. About the Log(): I see immediately in thread and main 5 seconds later.
What is my mistake here?
I think the syntax you’re looking for is:
Thread {
// your execution code
}.start()
Also read this answer for further information.
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.
I am developing an application using Android SDK. In this application I am facing a problem when an Activity starts a Thread. The new Thread starts an AsyncTask, but the Thread has to wait for completion of the AsyncTask execution.
Is it possible to start AsyncTask in a thread, and if so, how should it be implement?
Please can anyone share your experience with me about this kind of tasks.
Thanks in advance
You should not create an AsyncTask from a thread other than main thread.
If you should wait anyway, why create AsyncTask? perform it on the thread.
just say thread to sleep for some times and then check a variable again like this
in below code someValue was setted in asynctask postExecute method
new Thread(new Runnable(){
#Override
public void run(){
while(!someValue) {
try {
Thread.sleep(200);
} catch {
Log.i("LOG", "ERROR");
}
}
Log.i("LOG", "Async Task Finished");
}
}).start();