Creating a new Thread and using Thread.sleep()
public class TestThread implements Runnable {
public static void main(String[] args) {
TestThread threadJob = new TestThread();
Thread myThread = new Thread(threadJob);
myThread.start();
System.out.printf("Back in main\n");
}
@Override
public void run() {
doStuff();
System.out.println("Bottom of the stack");
}
public void doStuff() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) { //pretty unlikely to get an InterruptedException. Java added it for other language specific reasons
e.printStackTrace();
}
doMoreStuff();
System.out.println("Second on the stack");
}
public void doMoreStuff() {
System.out.println("Top of the stack");
}
}
//the way we can get control of what the threadscheduler runs is by using Thread.sleep(). In this example "Back in main" will always print first, because the created thread moves from a running to runnable state due to the Thread.sleep(). The thread scheduler will move back to the main method, before moving back to the created thread