Java run thread lambda

How to use Java Lambda expression to create thread via Runnable

Lambda expressions (Project Lambda — JSR 335) are a new and important feature of the upcoming Java SE 8 platform (JSR 337). They can be used to represent one method interface (also known as functional interface) in a clear and concise way using an expression in the form of:

(argument list) -> body

In this article, we see how Lambda expressions can simplify the creation of a new thread.

1. Create a Java thread via Runnable using Classic Code

Before Java 8, we create and start a thread by creating an anonymous class that implements the Runnable interface, as shown in the following code:

Runnable task1 = new Runnable() < @Override public void run()< System.out.println("Task #1 is running"); >>; Thread thread1 = new Thread(task1); thread1.start();
Thread thread1 = new Thread(new Runnable() < @Override public void run()< System.out.println("Task #1 is running"); >>); thread1.start();

2. Create a Java thread via Runnable using Lambda expression

With Lambda expressions come with Java 8, the above code can be re-written more concisely. For example:

// Lambda Runnable Runnable task2 = () -> < System.out.println("Task #2 is running"); >; // start the thread new Thread(task2).start();

It’s much more simple, isn’t it? By using Lambda expression, you don’t have to write the boilerplate code: declarations of the anonymous class and the run() method.

And the following code snippet is for test program that demonstrates creating threads using both classic and Lambda approaches:

package net.codejava.lambda; /** * This simple program demonstrates how to use Lambda expressions to create * and run threads. * * @author www.codejava.net */ public class RunnableLambdaExample < public static void main(String[] args) < System.out.println(Thread.currentThread().getName() + ": RunnableTest"); // Anonymous Runnable Runnable task1 = new Runnable()< @Override public void run()< System.out.println(Thread.currentThread().getName() + " is running"); >>; // Passing a Runnable when creating a new thread Thread thread2 = new Thread(new Runnable() < @Override public void run()< System.out.println(Thread.currentThread().getName() + " is running"); >>); // Lambda Runnable Runnable task3 = () -> < System.out.println(Thread.currentThread().getName() + " is running"); >; Thread thread1 = new Thread(task1); thread1.start(); thread2.start(); new Thread(task3).start(); > >

Output of this program may be different on each run because there are 3 threads started simultaneously. For example:
Run #1:

main: RunnableTest Thread-1 is running Thread-0 is running Thread-2 is running
main: RunnableTest Thread-1 is running Thread-2 is running Thread-0 is running

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Читайте также:  Php send http error message

Источник

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 ):

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

Источник

How to use Java Lambda expression to create thread via Runnable

Lambda expressions (Project Lambda — JSR 335) are a new and important feature of the upcoming Java SE 8 platform (JSR 337). They can be used to represent one method interface (also known as functional interface) in a clear and concise way using an expression in the form of:

(argument list) -> body

In this article, we see how Lambda expressions can simplify the creation of a new thread.

1. Create a Java thread via Runnable using Classic Code

Before Java 8, we create and start a thread by creating an anonymous class that implements the Runnable interface, as shown in the following code:

Runnable task1 = new Runnable() < @Override public void run()< System.out.println("Task #1 is running"); >>; Thread thread1 = new Thread(task1); thread1.start();
Thread thread1 = new Thread(new Runnable() < @Override public void run()< System.out.println("Task #1 is running"); >>); thread1.start();

2. Create a Java thread via Runnable using Lambda expression

With Lambda expressions come with Java 8, the above code can be re-written more concisely. For example:

// Lambda Runnable Runnable task2 = () -> < System.out.println("Task #2 is running"); >; // start the thread new Thread(task2).start();

It’s much more simple, isn’t it? By using Lambda expression, you don’t have to write the boilerplate code: declarations of the anonymous class and the run() method.

Читайте также:  Аргументы метода sort python

And the following code snippet is for test program that demonstrates creating threads using both classic and Lambda approaches:

package net.codejava.lambda; /** * This simple program demonstrates how to use Lambda expressions to create * and run threads. * * @author www.codejava.net */ public class RunnableLambdaExample < public static void main(String[] args) < System.out.println(Thread.currentThread().getName() + ": RunnableTest"); // Anonymous Runnable Runnable task1 = new Runnable()< @Override public void run()< System.out.println(Thread.currentThread().getName() + " is running"); >>; // Passing a Runnable when creating a new thread Thread thread2 = new Thread(new Runnable() < @Override public void run()< System.out.println(Thread.currentThread().getName() + " is running"); >>); // Lambda Runnable Runnable task3 = () -> < System.out.println(Thread.currentThread().getName() + " is running"); >; Thread thread1 = new Thread(task1); thread1.start(); thread2.start(); new Thread(task3).start(); > >

Output of this program may be different on each run because there are 3 threads started simultaneously. For example:
Run #1:

main: RunnableTest Thread-1 is running Thread-0 is running Thread-2 is running
main: RunnableTest Thread-1 is running Thread-2 is running Thread-0 is running

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Источник

How To Create A Thread Using Lambda Expressions In Java 8 and Using Runnable With Lambda?

Twitter Facebook Google Pinterest

A quick guide to create a thread using java 8 lambda expression instead of overriding the Runnable interface run() method.

1. Overview

In this tutorial, we’ll learn how to create a thread using lambda expression in java 8 and beyond versions.

Lambda expressions are newly added concept in the JDK 1.8 version and that introduced the functional programming concepts such as assigning the method to the variable.

Important point is that we can directly implementation for the abstract method of interface with java 8 lambda instead of overriding the method by implementing the interface.

How To Create A Thread Using Lambda Expressions In Java 8?

2. Example To Create New Thread Via Runnable Using Lambda in Java 8

In the below program, we are going to create the Thread and implementing the Runnable interface run() method using Lambda Expression.

By using Lambda, we can skip the implements Runnable interface and overriding the run() method which holds the core thread logic.

If you are new to java 8 lambda, you can read the complete set of rules to Lambda Expressions.

And also we can avoid new Runnable() and implementing the run() method using lamdba. Because, once you start writing the code using java 8 then compiler knows that you are using Function Interface Runnable which has only run() method.

Читайте также:  Learn about php programming

So when you pass Runnable lambda to Thread constructor, it treats as passing implementation of Runnable interface with run() method.

Next, Look at the below example program to create a java thread via runnable using lambda expression

package com.javaprogramto.threads.java8; public class CreateThreadLambda < public static void main(String[] args) < // Thread creation using java 8 lambda using runnable Thread evenNumberThread = new Thread(() -> < // this logic is implementation of run() method to print only even numbers for (int i = 0; i < 20; i++) < if (i % 2 == 0) < System.out.println("Even Number Thread : "+i); try < Thread.sleep(1000); >catch (InterruptedException e) < e.printStackTrace(); >> > >); // starting the thread evenNumberThread.start(); // Printing the odd numbers from main thread. for (int i = 0; i < 20; i++) < if (i % 2 == 1) < System.out.println("Odd Number Thread : "+i); try < Thread.sleep(1000); >catch (InterruptedException e) < e.printStackTrace(); >> > > >
Even Number Thread : 0 Odd Number Thread : 1 Odd Number Thread : 3 Even Number Thread : 2 Odd Number Thread : 5 Even Number Thread : 4 Even Number Thread : 6 Odd Number Thread : 7 Odd Number Thread : 9 Even Number Thread : 8 Odd Number Thread : 11 Even Number Thread : 10 Odd Number Thread : 13 Even Number Thread : 12 Even Number Thread : 14 Odd Number Thread : 15 Even Number Thread : 16 Odd Number Thread : 17 Even Number Thread : 18 Odd Number Thread : 19

3. Conclusion

In this article, we’ve seen how to create a new thread using lambda java 8 with example program to print even and odd number in unordered.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

JavaProgramTo.com: How To Create A Thread Using Lambda Expressions In Java 8 and Using Runnable With Lambda?

A quick guide to create a thread using java 8 lambda expression instead of overriding the Runnable interface run() method.

Источник

Оцените статью