3

I'm starting a thread which loops indefinitely until a certain event occurs. The problem is, I want to start this thread, and then return to the normal execution of my program. However, after starting the thread, the code seems to get stuck.

Code:

public void init()
{
   Runnable thread = new Runnable()
   {
     public void run()
     {
        while(something)
        {
           //do something
        }
     }        
   };
   System.out.println("Starting thread..");
   new Thread(thread).run();
   System.out.println("Returning");
   return;
}

When I start this, I get the output "Starting thread" but I don't get "returning" until the conditions for the while loop in the run() stop being true.

Any ideas how I can make it work asynchronously?

4

4 回答 4

13

Use start rather than run to start a Thread. The latter just invokes the run method synchronously

new Thread(thread).start();

Read: Defining and Starting a Thread

于 2013-09-17T16:52:24.040 回答
1

You may try this in your code:-

new Thread(thread).start();

like:-

public void init()
{
   Runnable thread = new Runnable()
   {
     public void run()
     {
        while(something)
        {
           //do something
        }
     }        
   };
   System.out.println("Starting thread..");
   new Thread(thread).start();    //use start() instead of run()
   System.out.println("Returning");
   return;
}
于 2013-09-17T16:53:02.867 回答
1

You want to call new Thread(thread).start() instead of run().

于 2013-09-17T16:53:17.680 回答
-1

Are you sure about your approach? You say:

The thread should loop indefinitely until certain event occurs.

that's an enormous loss of computational resource, the program is principally bound to get slow & fail. You may want to put the thread in wait() mode and catch InterruptedException to wake it up upon occurrence of your event of interest. If this preliminary understanding of what you are trying to accomplish is true then Id' strongly suggest you to revise your approach. Computing resource is expensive, don't waste it in relentless looping.

于 2013-09-17T17:05:52.003 回答