当前位置:   article > 正文

【Java 8 新特性】Java 8 Runnable和Callable使用Lambda表达式示例(带参数)_i -> new runnable().run == intconsumer

i -> new runnable().run == intconsumer


Java 8中, RunnableCallable两个接口均已通过 @FunctionalInterface进行注释。

我们可以使用lambda表达式实现run()call()方法。

在此页面上,我们还将提供如何将参数传递给RunnableCallable方法。

Java 8 Runnable Lambda示例(带参数)

Java 8支持lambda表达式。

Java 8中,已使用@FunctionalInterface注释了Runnable接口。

现在,我们可以使用lambda表达式创建Runnable实例。

Runnable r = () -> System.out.println("Hello World!");
Thread th = new Thread(r);
th.start(); 
  • 1
  • 2
  • 3

上面的代码等同于下面的代码。

Runnable r = new Runnable() {
   @Override
   public void run() {
	System.out.println("Hello World!");
   }
};
Thread th = new Thread(r);
th.start(); 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

如果需要在run()方法中编写多行代码,可以使用如下所示的lambda表达式进行操作。

Runnable r = () -> {
	Consumer<Book> style = (Book b) -> System.out.println("Book Id:"+b.getId() + ", Book Name:"+b.getName());
	list.forEach(style);
}; 
  • 1
  • 2
  • 3
  • 4

要将参数传递给我们的run()方法,我们应该使用final修饰符。

final List<Book> list =  Arrays.asList(new Book(1, "Ramayan"), new Book(2, "Mahabharat"));
Runnable r = () -> {
	Consumer<Book> style = (Book b) -> System.out.println("Book Id:"+b.getId() + ", Book Name:"+b.getName());
	list.forEach(style);
}; 
  • 1
  • 2
  • 3
  • 4
  • 5

现在,找到使用Thread类带有lambda表达式的Java 8 Runnable的完整示例。

Java8RunnableDemo.java

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import com.concretepage.Book;
public class Java8RunnableDemo {
	public static void main(String[] args) {
		final List<Book> list =  Arrays.asList(new Book(1, "Ramayan"), new Book(2, "Mahabharat"));
		Runnable r1 = () -> list.forEach(Book::print);
		Thread th1 = new Thread(r1);
		th1.start();
		Runnable r2 = () -> {
			Consumer<Book> style = (Book b) -> System.out.println("Book Id:"+b.getId() + ", Book Name:"+b.getName());
			list.forEach(style);
		};
		Thread th2 = new Thread(r2);
		th2.start();
	}
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

Book.java

public class Book {
        public int id;
        public String name;
        public Book(int id, String name){
            this.id = id;
            this.name = name;
        }
        public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void print(){
               System.out.println("id:"+id + ", Name:"+name);
        }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

输出

id:1, Name:Ramayan
Book Id:1, Book Name:Ramayan
id:2, Name:Mahabharat
Book Id:2, Book Name:Mahabharat
  • 1
  • 2
  • 3
  • 4

查找示例代码以使用ExecutorService运行Runnable实例。

Java8RunnableDemoExecutor.java

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import com.concretepage.Book;
public class Java8RunnableDemoExecutor {
	public static void main(String[] args) {
		final List<Book> list =  Arrays.asList(new Book(1, "Ramayan"), new Book(2, "Mahabharat"));
		ExecutorService service =  Executors.newFixedThreadPool(2);
		Runnable r1 = () -> list.forEach(Book::print);
		service.execute(r1);
		Runnable r2 = () -> {
			Consumer<Book> style = (Book b) -> System.out.println("Book Id:"+b.getId() + ", Book Name:"+b.getName());
			list.forEach(style);
		};
		service.execute(r2);
	}
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

输出

id:1, Name:Ramayan
id:2, Name:Mahabharat
Book Id:1, Book Name:Ramayan
Book Id:2, Book Name:Mahabharat
  • 1
  • 2
  • 3
  • 4

Java 8 Callable Lambda示例(带参数)

Java 5中引入了Callable <V>接口,其中V是返回类型。

Java 8中,Callable接口已使用@FunctionalInterface注释。

现在在Java 8中,我们可以使用lambda表达式创建Callable对象,如下所示。

Callable<Integer> callableObj = () -> { return 2*3; };
  • 1

上面的代码等同于下面的代码片段。

Callable<Integer> callableObj = new Callable<Integer>() {
	@Override
	public Integer call() throws Exception {
		return 2*3;
	}
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

要将参数传递给我们的call()方法,我们应该使用final修饰符。

final int val = 10; 
Callable<Integer> callableObj = () -> { return 2*val; };
  • 1
  • 2

现在,找到使用ExecutorService带有lambda表达式的Callable的完整示例。

Java8CallableDemo.java

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Java8CallableDemo {
	public static void main(String[] args) {
		final List<Integer> integers =  Arrays.asList(1,2,3,4,5);
		Callable<Integer> callableObj = () -> {
			int result = integers.stream().mapToInt(i -> i.intValue()).sum();
			return result;
		};
		ExecutorService service =  Executors.newSingleThreadExecutor();
		Future<Integer> future = service.submit(callableObj);
		Integer result=0;
		try {
			result = future.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("Sum = "+result);
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

输出

Sum = 15
  • 1

参考文献

【1】Java 8 Runnable and Callable Lambda Example with Argument

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号