Monday, April 30, 2007

How to code an inline Java Thread

This is an example for how to create an inline Java thread and launch it. The Thread Javadoc describes it in pieces and this is a complete example.

import java.util.Date;

public class InlineThreadDemo {

public static void main(String[] args) {
System.out.println(
"parent thread " + new Date(System.currentTimeMillis()));
// launch child thread using inline declaration
new Thread(
new Runnable() {
public void run() {
try {
Thread.sleep(10 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(
"child thread " + new Date(System.currentTimeMillis()));
}
}).start();
System.out.println(
"parent thread " + new Date(System.currentTimeMillis()));
}
}

The output from the program will be someting like this.

parent thread Mon Apr 30 22:14:02 ADT 2007
parent thread Mon Apr 30 22:14:02 ADT 2007
child thread Mon Apr 30 22:14:12 ADT 2007

1 comment:

Anonymous said...

Thanks a lot for this. Turned out to be very helpful for me.