I have the following code snippet:
public class A {
public static void main(String[] arg) {
new Thread() {
public void run() {
Not exactly sure this is what you are asking but you can do something like:
new Thread() {
public void run() {
System.out.println("blah");
}
}.start();
Notice the start()
method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.
Better than creating an anonymous Thread
class is to create an anonymous Runnable
class:
new Thread(new Runnable() {
public void run() {
System.out.println("blah");
}
}).start();
Instead overriding the run()
method in the Thread
you inject a target Runnable
to be run by the new thread. This is a better pattern.
The entire new
expression is an object reference, so methods can be invoked on it:
public class A {
public static void main(String[] arg)
{
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
}
}