I have the following code snippet:
public class A {
public static void main(String[] arg) {
new Thread() {
public void run() {
Leaving this here for future reference, but its an answer too.
new Thread(() -> whatever()).start();
Just call start()
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
Since anonymous classes extend the given class you can store them in a variable.
eg.
Thread t = new Thread()
{
public void run() {
System.out.println("blah");
}
};
t.start();
Alternatively, you can just call the start method on the object you have immediately created.
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
// similar to new Thread().start();
Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).
eg
new Thread(new Runnable()
{
@Override
public void run() {
System.out.println("blah");
}
}).start();
I'm surprised that I didn't see any mention of Java's Executor framework for this question's answers. One of the main selling points of the Executor framework is so that you don't have do deal with low level threads. Instead, you're dealing with the higher level of abstraction of ExecutorServices. So, instead of manually starting a thread, just execute the executor that wraps a Runnable. Using the single thread executor, the Runnable
instance you create will internally be wrapped and executed as a thread.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// ...
ExecutorService threadExecutor = Executors.newSingleThreadExecutor();
try {
threadExecutor.execute(
new Runnable() {
@Override
public void run() {
System.out.println("blah");
}
}
);
} finally {
threadExecutor.shutdownNow();
}
For convenience, see the code on JDoodle.
Add: now you can use lambda to simplify your syntax. Requirement: Java 8+
public class A {
public static void main(String[] arg)
{
Thread th = new Thread(() -> {System.out.println("blah");});
th.start();
}
}
You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start()
without even using a local variable:
new Thread()
{
public void run() {
System.out.println("blah");
}
}.start();
... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:
Thread t = new Thread() {
public void run() {
System.out.println("blah");
}
};
t.start();