Friday, April 5, 2013

java - How to call/execute a method and continue without waiting for it

Sometimes you may have found some situations where you need to call another method from one of your methods, but need to continue the current method without waiting for the completion of the other method.
The way to accomplish this task is this.

First create a Runnable object. Inside the run() method call the second method like below.
private Runnable r = new Runnable() {
  @Override
  public void run() {
    sayHello();//Your method
  }
};
Now when you want to call that method call it like this.
new Thread(r).start();

Following is a working example
public class MyClass {

  private static Runnable r = new Runnable() {
    @Override
    public void run() {
      sayHello();
    }
  };

  public static void main(String[] args) {
    System.out.println("before calling sayHello()");
    new Thread(r).start();
    System.out.println("I didn't wait untill sayHello() finished his job");
  }

  private static void sayHello() {
    for(int i = 0; i < 10; i++) {
      System.out.println("Hello");
    }
  }
}

No comments:

Post a Comment