简体   繁体   English

Java:如何在线程启动后继续执行?

[英]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. 当我开始这个时,我得到输出“Starting thread”但是我没有得到“返回”,直到run() while循环的条件停止为真。

Any ideas how I can make it work asynchronously? 有什么想法我可以让它异步工作吗?

Use start rather than run to start a Thread . 使用start而不是run来启动Thread The latter just invokes the run method synchronously 后者只是同步调用run方法

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. 您可能希望将线程置于wait()模式并捕获InterruptedException以在发生您感兴趣的事件时将其唤醒。 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. 计算资源是昂贵的,不要浪费在无情的循环中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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