|
-
Mar 25th, 2008, 03:18 AM
#4
Thread Starter
PowerPoster
Re: Unable to stop/suspend the thread.
 Originally Posted by ComputerJy
There is always a work around
Code:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Util {
private static boolean running = true;
public static void main(String[] args) {
try {
Thread countThread = new Thread(new Runnable() {
public void run() {
int counter = 1;
while (counter != 0 && running) {
// Condition to change
try {
System.out.println(counter++);
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
});
countThread.start();
System.out.println("Press type anything and press enter to stop counting");
System.in.read();
running = false;
} catch (IOException ex) {
Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I got what you have done here. But I have one question here.
In my code I set the sleep time to 10 seconds (10000 milliseconds actually). If I suspends the thread, it is suspend after 10 seconds. Not suspended at the same time I call to suspend.
Here is my code.
Code:
boolean threadSuspend = false;
Thread processThread;
int counter;
public void init(){
counter = 0;
processThread = new Thread(this);
processThread.start();
}
public void run(){
while(true){
try {
System.out.println(counter++);
Thread.sleep(10000);
synchronized(this){
while(threadSuspend){
try{
wait();
}
catch(Exception ex){
Logger.getLogger(Processing.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
catch (InterruptedException ex) {
Logger.getLogger(Processing.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I've done this to suspend the thread.
Code:
synchronized(appProcess){
appProcess.threadSuspend = true;
}
appProcess is the thread class actually.
To resume the thread do following.
Code:
synchronized(appProcess){
appProcess.threadSuspend = false;
appProcess.notify();
}
Do you know why this is happened. Actually it suspend and resume the thread at the same if I have done it after 10 seconds. If I try to suspend or resume within the 10 second, it happened after reach to 10 second limit.
“victory breeds hatred, the defeated live in pain; happily the peaceful live giving up victory and defeat” - Gautama Buddha
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|