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.
@Override
public void run() {
sayHello();//Your method
}
};
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");
}
}
}
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