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. As a little bonus I also show the Java lambda syntax in other situations, such as with an ActionListener, and several “handler” examples, including when a lambda has multiple parameters.

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();

Note: There’s an interesting approach documented here:

def run2() = {println("hi2")}
new Thread(() => run2).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();

Java 8 ActionListener examples

With Java 8 lambdas this ActionListener/ActionEvent code:

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        handleMakeTheImageLargerAction();
}};

can be rewritten as this:

ActionListener actionListener = actionEvent -> handleMakeTheImageLargerAction();

More Java lambda syntax examples

While I’m in the Java lambda neighborhood, here are some more examples of the Java lambda syntax, in this case showing how I use the lambda syntax for some java.awt.Desktop event handlers:

desktop.setAboutHandler(e ->
    JOptionPane.showMessageDialog(null, "About dialog")
);
desktop.setPreferencesHandler(e ->
    JOptionPane.showMessageDialog(null, "Preferences dialog")
);
desktop.setQuitHandler((e,r) -> {
        JOptionPane.showMessageDialog(null, "Quit dialog");
        System.exit(0);
    }
);

That code comes from my Java 10 on MacOS About, Preferences, and Quit handlers example.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.