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.
开发者_C百科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 anyInterruptedExceptions
- 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();
}
}
精彩评论