Lambda_06 函数表达式创建线程对象|8月更文挑战

329 阅读1分钟

这是我参与8月更文挑战的第21天,活动详情查看:8月更文挑战

1、创建Thread对象,重写匿名内部类的run方法

2、匿名内部类 使用Lambda表达式编写

3、简化编写线程代码的冗余度

代码示例

public class Lambda07 {
    public static void main(String[] args) {
        /**
         * Java 匿名内部类实现线程
         */
        Thread thread0 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("使用java内部类实现一个线程");
            }
        });
        thread0.start();

        /**
         * 使用Lambda实现一个线程
         */
        Thread thread1 = new Thread(() -> {
            System.out.println("Lambda实现一个线程");
            System.out.println("这就完成了");
        });
        thread1.start();
    }
}

如果只有一行代码可以这样简写

Thread thread2 = new Thread(()-> System.out.println("如果只有一行代码可以这样简写"));
        thread2.start();

通过Callable和Future创建线程

public interface Callable{ V call() throws Exception; }

  • 创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。
  • 创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。(FutureTask是一个包装器,它通过接受Callable来创建,它同时实现了Future和Runnable接口。)
  • 使用FutureTask对象作为Thread对象的target创建并启动新线程。
  • 调用FutureTask对象的get()方法来获得子线程执行结束后的返回值
public class CallableThreadTest implements Callable<Integer> {
 
    @Override
    public Integer call() throws Exception {
        int i = 0;
        for (; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
        return i;
    }
 
    public static void main(String[] args) {
        CallableThreadTest ctt = new CallableThreadTest();
        FutureTask<Integer> ft = new FutureTask<>(ctt);
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
            if (i == 2) {
                new Thread(ft, "有返回值的线程").start();
            }
        }
        try {
            System.out.println("子线程的返回值:" + ft.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
 
}

使用Lambda表达式

public class CallableThreadTest {
    public static void main(String[] args) {
        FutureTask<Integer> ft = new FutureTask<>(() -> {
            int i = 0;
            for (; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
            return i;
        });
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName() + " 的循环变量i的值" + i);
            if (i == 2) {
                new Thread(ft, "有返回值的线程").start();
            }
        }
        try {
            System.out.println("子线程的返回值:" + ft.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}