The Java 8 lambda Thread and Runnable syntax and examples

As a quick note, here are some examples of the Java 8 lambda Thread and Runnable syntax.

Java 8 Thread/Runnable lambda syntax

First, here’s the Java 8 lambda syntax for a Runnable, where I create a Runnable and pass it to a Thread:

Runnable runnable = () -> { 
    // your code here ...
};
Thread t = new Thread(runnable);
t.start();

Here’s the Java 8 Thread lambda syntax (without a Runnable):

Thread t = new Thread(() -> {
    // your code here ...
});

You can also use this lambda approach to create a Thread, without creating a reference (variable) to the thread:

new Thread(() -> // your code here).start();

The older Thread and Runnable syntax

If you can’t use Java 8 lambdas — or don’t want to — here’s the pre-lambda thread syntax using a Runnable:

// pre java 8 lambdas
Thread t = new Thread(new Runnable() {
    public void run() {
        // your code here ...
    }
});

t.start();

Here’s the old Thread syntax, using the anonymous class approach:

Thread thread = new Thread() {
    public void run() {
        // your code here
    }
}

thread.start();

You can also create a class to extend a Thread and then run it, like this:

public class MyThread extends Thread {
    public void run() {
        // your code here
    }
}

MyThread myThread = new MyThread();
myTread.start();

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.