I can't finish thread (runnable), how it is? - java

Thread thread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yippi);
final Handler hn=new Handler();
final TextView text=(TextView)findViewById(R.id.TextView01);
final Runnable r = new Runnable()
{
public void run()
{
text.settext("hi");
}
};
thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1750);
hn.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
thread.stop();}
The code here. I can not stop the runnable thread. Also, thread.stop() and thread.destroy() are deprecated. Can somebody help me? And also I don't understand how to stop the thread with the thread.interrupt() method. What's wrong?

The JavaDoc for Thread.stop() lists the following article as explanation for why stop() is deprecated: http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Most uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running. To ensure prompt communication of the stop-request, the variable must be volatile (or access to the variable must be synchronized).
interrupt() is more suitable to stop some Thread from waiting for something, that is probably not coming anymore. If you want to end the thread, it's best to let its run() method return.

Create a boolean variable to stop the thread and use it in while(boolean) instead of while(true).

You can use Thread.interrupt() to trigger the InterruptedException within your thread. I've added code below that demonstrates the behavior. The mainThread is where your code would be and the timer Thread is just used to demonstrate delayed triggering of the interrupt.
public class Test {
public static void main(String[] args) {
final Thread mainThread = new Thread() {
#Override
public void run() {
boolean continueExecution = true;
while (continueExecution) {
try {
sleep(100);
System.out.println("Executing");
} catch (InterruptedException e) {
continueExecution = false;
}
}
}
};
mainThread.start();
Thread timer = new Thread() {
#Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping recurring execution");
mainThread.interrupt();
}
};
timer.start();
}
}

You can use interrupt method of Thread to try stop a thread, like below code.
May be it`s useful to you.
public class InterruptThread {
public static void main(String args[]){
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
System.out.println("Thread is Runing......");
sleep(1000);
}
} catch (InterruptedException e) {
// restore interrupted status
System.out.println("Thread is interrupting");
Thread.currentThread().interrupt();
}
}
};
thread.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Will Interrupt thread");
thread.interrupt();
}
}

Related

runOnUi slows down the app and make it forced close

i am generating a random string for infinite time and setting it to a EditText.
when i was not using runOnUi app was working on newer devices which have high capability. but it crashes on older model when i start the thread and gave error(called from wrong thread exception)
Then i used runOnUi but it makes the super slow and force close it.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
tryPass.setText(getAlphaNumericString());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
});
thread.start();
You're trying to block UI thread by calling Thread.sleep(2000); on UI thread.
Try this way:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
tryPass.setText(getAlphaNumericString());
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();

delay inside while loop not working

i'm trying to make a delay inside while loop using Thread.sleep() method . here is my code :
new Thread(new Runnable() {
#Override
public void run() {
z=0;
while (z<45){
z++;
handler.post(new Runnable() {
#Override
public void run() {
time.setText(Integer.toString(45-z));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
this code was working and suddenly a problem occurred . it started to make a delay less than one minute , sumtimes 500 ms and sumtimes less than that
Instead if using a different thread, Thread.sleep(), Handler and while loop you can try only with Handler like this,
private int timerCount = 0;
private static Handler myHandler = new Handler();
private void runVVRunnable() {
myHandler.postDelayed(runnable, 1000);
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
timerCount++;
if ((time == null)) {
return;
}
if (timerCount <= 45) {
time.setText(Integer.toString(timerCount));
runVVRunnable();
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
myHandler.removeCallbacks(runnable);
}
you can just call runVVRunnable() it will do the same process which you are doing while loop
Just a guess but when sleeping/waiting on Java thread you need to try-catch InterruptedException.
This exception is thrown when "someone" calls interrupt() on your thread.
This will cause the thread to wake up from sleep early than expected.
Check if you catch InterruptedException before your thread terminated.

cannot stop progress bar on Android using Thread.interrupt

I am running into a minor issue that I don't understand. I have a simple progress bar but Thread.interrupt does not stop the thread. I have to hack it a global variable. I wonder if anyone can stop the issue.
I tried this thread, but did not work for me:
How to stop a thread(progressbar) in android
here's the code with the hacks
// Start lengthy operation in a background thread
calcThread = new Thread
(
new Runnable()
{
public void run()
{
Thread current = Thread.currentThread();
//while (!current.isInterrupted()) // this does not
while (threadLoop) // this hack works
{
doWork();
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
// Update the progress bar
mHandler.post(new Runnable() {
public void run() {
mProgress.setProgress(mProgressStatus);
}
});
}
Log.d(TAG, "out of thread loop");
}
}
);
calcThread.start();
now where I try to stop the thread
public void onClickAbout(View view)
{
if (view.getId() == R.id.buttonAbout)
{
Log.d(TAG, "onButtonPressed");
calcThread.interrupt(); // This does not work
threadLoop = false; // this works.
}
}
Why do I have to hack a global? In other words, why Thread.interrupt does not stop the thread.
thx!
Why don't you try the following
Thread background = new Thread() {
public void run() {
try{
for(int s=0;s<=100;s++)
{
s=s+20;
sleep(1000);
progressbar.setProgress(s);
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
//do some thing after you finish thread
}
}
};
background.start();
It doesn't work because you're catching InterruptedException and ignoring it. The thread is no longer interrupted after the exception is thrown. (See this Q&A.) But k0sh is right, you should use an AsyncTask.

Thread won't enter synchronized block

I have a Button in my android app which must run a continuous action while holding it down, for that I created an onTouchListener to handle such issue, my structure is when catching ACTION_DOWN event a thread with a while(true) loop runs, then when catching ACTION_UP event that thread stopped via wait() in order to resume it's looping again upon holding down, the problem is that when trying to execute thread.wait() the thread doesn't enter the synchronized block and doesn't wait, but it stops the execution of runOnUIThread which exists in that thread, and after I press any button after that the app crashes and gives me ANR Exception : Input dispatching timed out:
// the thread declaratrion
test = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
// still loops here
value = value + 1;
runOnUiThread(new Runnable() {
public void run() {
// doesn't go here anymore
mTextView.setText(Integer.toString(value));
}
});
// still loops here
synchronized (test) {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
// the onTouchListener
case MotionEvent.ACTION_DOWN:
if (!test.isAlive()) {
synchronized (test) {
test.start();
}
} else {
synchronized (test) {
test.notify();
}
}
break;
case MotionEvent.ACTION_UP:
// accepts the action
synchronized (test) {
try {
// doesn't goes here
test.wait(); // doesn't execute
} catch (InterruptedException e) {
e.printStackTrace();
}
}
break;
default:
break;
Probably you use too low level API for your needs. Just look at http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
One thing I see is potential dangerous is that in your separate thread, you are waiting inside a synchronized statement. So when that guy is sleeping, it takes the lock with him, and therefore in your onTouchListener, none could grabbed the lock but to wait. And because the onTouchListener is controlled in the framework, it may stop running if it waits too long. I did a simple test here to prove it.
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
final Object globalLock = new Object();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
synchronized (globalLock) {
System.out.println("thread1 grabbed the lock.");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread1 returned the lock.");
}
}
});
t1.start();
Thread.sleep(200);
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("thread2 is waiting for the lock...");
synchronized (globalLock) {
System.out.println("thread2 got the lock");
}
}
});
t2.start();
t1.join();
t2.join();
}
}

Thread in android not working as expected

I am following a guide that shows how to create a Pong game. There is a part, where I am supposed to create a Thread, and call a function that moves the ball.
This is the code I created:
package com.ozadari.pingpong;
public class PingPongGame extends Thread {
private Ball gameBall;
private PingPongView gameView;
public PingPongGame(Ball theBall,PingPongView mainView)
{
this.gameBall = theBall;
this.gameView = mainView;
}
#Override
public void run()
{
while(true)
{
this.gameBall.moveBall();
this.gameView.postInvalidate();
try
{
PingPongGame.sleep(5);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}}
The thread is called and working, but it doesn't print anything. I tried to cancel the infinte loop and make the loop run 100 times. After I wait a while, it prints to the screen as it should be after 100 runs, but it doesn't print anything in the middle.
What is the problem? How can I fix it?
Unsure from the code you've posted but anyway, you can use a handler and have it run once every second like so (change the time to what you want):
Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
//do your stuff here
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 1000);
http://developer.android.com/reference/android/os/Handler.html
You can also use a normal thread, and call start at the end.
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(1000);
handler.post(r);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();

Categories