Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a function that needs to perfom two operations, one which finishes fast and one which takes a long time to run. I want to be able to delegate the long running operation to a thread and I dont care when the thread finishes, but the threads needs to complete. I implemented this as shown below , but, my secondoperation never gets done as the function exits after the start() call. How I can ensure that the function returns but the second operation thread finishes its execution as well and is not dependent on the parent thread ?

public void someFunction(String data)
{
   smallOperation()
   SecondOperation a = new SecondOperation();
   Thread th = new Thread(a);
   th.Start();
}

class SecondOperation implements Runnable
{
  public void run(){
  // doSomething long running
 }
} 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
618 views
Welcome To Ask or Share your Answers For Others

1 Answer

public void someFunction(final String data) {
    shortOperation(data);
    new Thread(new Runnable() {
        public void run(){
            longOperation(data);
        }
    }).start();
}

If someFunction is called, the JVM will run the longOperation if

  1. the thread running it is not marked as a daemon (in the above code it is not)
  2. the longOperation() does not throw an exception and
  3. no calls to System.exit() is made in longOperation()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...