简体   繁体   中英

Java: How to continue execution after thread is started?

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?

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

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;
}

您想要调用new Thread(thread).start()而不是run()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM