Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function without waiting for it

Hi I was wondering if there was a way of calling a function/method (preferably in Python or Java) and continue execution without waiting for it.

Example:

def a():
    b()  #call a function, b()
    return "something"

def b():
    #something that takes a really long time
like image 444
Abs Avatar asked Jul 13 '12 02:07

Abs


1 Answers

Run it in a new thread. Learn about multithreading in java here and python multithreading here

Java example:

The WRONG way ... by subclassing Thread

new Thread() {
    public void run() {
        YourFunction();//Call your function
    }
}.start();

The RIGHT way ... by supplying a Runnable instance

Runnable myrunnable = new Runnable() {
    public void run() {
        YourFunction();//Call your function
    }
}

new Thread(myrunnable).start();//Call it when you need to run the function
like image 53
Ashwin Singh Avatar answered Oct 12 '22 09:10

Ashwin Singh