lambda表达式
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Ticket{
private int ticket = 30;
Lock lock = new ReentrantLock();
public void sale(){
lock.lock();
try {
if (ticket > 0){
System.out.println(Thread.currentThread().getName()+" 卖出了第"+ ticket-- +"张票"+" 还剩"+ticket+"张票");
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class Dugu {
public static void main(String[] args) {
final Ticket ticket = new Ticket();
new Thread(() -> {for (int i = 0; i < 40; i++) ticket.sale();},"A").start();
new Thread(() -> {for (int i = 0; i < 40; i++) ticket.sale();},"B").start();
new Thread(() -> {for (int i = 0; i < 40; i++) ticket.sale();},"C").start();
// sout
// new Thread(new Runnable() {
// public void run() {
// for (int i = 0; i < 40; i++) {
// ticket.sale();
// }
// }
// }, "C").start();
// new Thread(new Runnable() {
// public void run() {
// for (int i = 0; i < 40; i++) {
// ticket.sale();
// }
// }
// }, "B").start();
// new Thread(new Runnable() {
// public void run() {
// for (int i = 0; i < 40; i++) {
// ticket.sale();
// }
// }
// }, "A").start();
}
}
函数式接口
//@FunctionalInterface //该注解代表函数式接口,如果符合函数式接口的表达,可以不加
interface Foo{
//如果式函数式接口,普通方法只能定义一个,否则lambda无法找到默认方法
public int add(int x, int y);
//default方法可以随便加,数量不限,只要实现接口类,即便初始值被默认函数设置也无妨
default int mul(int x, int y){
return x * y;
}
//static方法不影响函数式接口,与静态变量相同,调用不需要实现类
public static int div(int x, int y){
return x/y;
}
}
public class LambdaTest {
public static void main(String[] args) {
Foo foo = (int x, int y) -> {
System.out.println("come in add method");
return x + y;
};
System.out.println(foo.add(3,9));
System.out.println(foo.mul(4,8));
System.out.println(Foo.div(18,3));
}
}
以上代码结果:
come in add method
12
32
6