创建线程5种方法

1、继承Thread,重写run方法,调用start启动

2、实现Runnable接口,重写run方法,调用start启动。

3、lambda表达式

public class MyThread {

    static class MyExtend extends Thread{
        @Override
        public void run() {
            System.out.println("Thread");
        }
    }

    static class MyRun implements Runnable{
        @Override
        public void run() {
            System.out.println("Thread");
        }
    }

    public static void main(String[] args) {
        new MyExtend().start();
        new Thread(new MyRun()).start();
        new Thread(()->{
            System.out.println("Thread");
        }).start();
    }
}

4、对于继承Thread和实现Runnable哪种更好?

  实现更好,java是单继承多实现的

5、线程池创建线程

        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(()->{
            System.out.println("Thread");
        });
        service.shutdown();    

6、实现Callable接口

  因为实现Runnale接口返回值是写死的void,不灵活,Callable接口返回值可以自己设定

public class MyCallable implements Callable<String > {

    @Override
    public String call() throws Exception {
        return "success";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newCachedThreadPool();
        Future<String> submit = service.submit(new MyCallable());
        String s = submit.get();
        System.out.println(s);
        service.shutdown();
    }
}

  

 

posted @ 2022-03-05 11:02  showMeTheCodes  阅读(265)  评论(0编辑  收藏  举报