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.
The Java Thread/Runnable lambda syntax
First, here’s the lambda syntax for a Runnable
that was introduced with Java 8, and now works with Java 11, Java 14, Java 17, etc., where I create a Runnable
and pass it to a Thread
:
Runnable runnable = () -> {
// your code here ...
};
Thread t = new Thread(runnable);
t.start();
And here’s the Java Thread
lambda syntax (without a Runnable
):
Thread t = new Thread(() -> {
// your code here ...
});
You can also use this lambda approach to create a Java 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.