Reputation: 498
just a little question, i want to stiop the following thread, but i have no idea how i should do. Please help me. Googles help wasnt useful this time.
new Thread(){
public void run() {
while(!isInterrupted()){
try {
if (sock1!=null){
sock1.setTcpNoDelay(true);
if (btsar1.length > 0) {
dos1 = new DataOutputStream(sock1.getOutputStream());
bwrtr1 = new BufferedWriter(new OutputStreamWriter(
dos1), 300);
dos1.write(btsar1);
set1free = false;
Log.e("Communication", "written(1.1)");
Reader1.reader(4);}
}} catch (IOException e) {
e.printStackTrace();
}catch (NullPointerException e2){
e2.printStackTrace();
}
}
}}.start();
//.interrupt(); <-- or kinda that...
Can someone provide a good working thing, to stop this?
Upvotes: 0
Views: 118
Reputation: 20751
Thread.interrupt
method is for to stop a thread that waits for long periods (e.g., for input)
Take a look at this Article - How to Stop a Thread or a Task
example
public void stop() {
Thread moribund = waiter;
waiter = null;
moribund.interrupt();
}
Upvotes: 0
Reputation: 13535
Thread t = new Thread(){
... // content unchanged
};
t.start();
.....
t.interrupt();
Upvotes: 1
Reputation: 22271
An idea: stop using anonymous threads!
Whenever you find yourself in a situation where your thread is doing something complicated, either create a separate class extending the thread, which can be used to control and monitor the behaviour, or use an abstract Future and a ThreadPool to do the work.
You will have an extremely unmaintainable and unextendable code if you keep using threads like this.
How to stop a thread gracefully?
bool keepWorking = true;
while(keepWorking) {
// keep working
}
synchronized void stopWork() {
keepWorking = false;
}
// in other thread
threadObj.stopWork();
Upvotes: 0
Reputation: 328845
You just need a reference to your thread:
Thread t = new Thread(...);
Then you can interrupt it:
t.interrupt();
Upvotes: 1
Reputation: 13821
The best way to terminate a thread is to let it finish. So add a boolean flag in your while
, and have method (or otherwise) expose it so it can be set to false. Then your thread would naturally exit after the interation has finished.
Upvotes: 0