HowTo- thread stop

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() {
            try {
                if (sock1!=null){
                    if (btsar1.length > 0) {
                        dos1 = new DataOutputStream(sock1.getOutputStream());
                        bwrtr1 = new BufferedWriter(new OutputStreamWriter(
                                dos1), 300);
                            set1free = false;
                    Log.e("Communication", "written(1.1)");
                    }} catch (IOException e) {
                }catch (NullPointerException e2){
//.interrupt(); <-- or kinda that...

Can someone provide a good working thing, to stop this?


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.

You just need a reference to your thread:

Thread t = new Thread(...);

Then you can interrupt it:


Thread t = new Thread(){
      ... // content unchanged

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

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


public void stop() {
            Thread moribund = waiter;
            waiter = null;

Need Your Help

Getting started with JDBC

eclipse ms-access jdbc odbc

I was getting started with JDBC and I was using the video mentioned here:

How to pass values to js in cocos2d-iphone jsbindings?

javascript ios objective-c cocos2d-iphone

I'm cooking a cocos2d-iphone(v2.1) project with jsbindings. The cocos2d view running main.js in my UIKit view works properly. Now I want to add a new feature to show different animation by user inp...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.