Hi! I have some excisting functions from a library and want to run some of them in a single thread. My Problem is: How can i stop this threads. I cant use a variable to interrupt the while loop of the thread cause i cant edit this functions
Printable View
Hi! I have some excisting functions from a library and want to run some of them in a single thread. My Problem is: How can i stop this threads. I cant use a variable to interrupt the while loop of the thread cause i cant edit this functions
the thread which i want to stop doesnt interact with any other thread. it only calculates some values and returns them afterwards. can i use stop() then safely
i found a small example how to stop a thread. perhaps you can use it for your problem. here is the code:
Code:class Thread1 extends Thread {
public void run() {
int i = 0;
System.out.println("while-loop starting ...");
while (!isInterrupted()) {
System.out.println(i++);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
System.out.println("interrupt received");
interrupt();
}
}
System.out.println("while-loop ended");
}
}
public class MyThread {
public static void main(String[] args) {
long start = System.currentTimeMillis();
Thread1 t = new Thread1();
t.start();
try {
Thread.sleep(2000);
System.out.println("call interrupt");
} catch (InterruptedException e) {
}
t.interrupt();
System.out.println("main ended");
System.out.println("duration of all tasks in millis: " + (System.currentTimeMillis() - start));
}
}
the thread is started inside the main function and also interrupted from the main function. in order to stop the thread you need this loop
while (!isInterrupted())
and inside the catch-block use the method interrupt() so that the boolean test in while becomes true and the thread ends. hope you understand the logic. good luck.
The OPs problem is:
It appears that he doesn't have the source for the looping thread, so he can't change it as per all your recommendationsQuote:
I cant use a variable to interrupt the while loop of the thread cause i cant edit this functions
oh, norm, for somebody who pretends to implement threads changing my code to fulfill the requirements should be an easy task: so declare a instance variable ex. stop in the class Thread1 with the value false, change the while to "while (!stop)". now from outside the class you can modify the stop instance variable to true and the thread will stop. if you need this code let me know.
i dont have the source code of any functions. they are from a library. i cant modify any while loop or implement stop variables.
But thx for your help
Spammer lmno947 reported
db