创建线程的五种方式

515 阅读1分钟

五种创建线程方式的本质都是New 一个Thread对象,调用它的Start方法。

1. 继承Thread类

public class MyThread extends Thread {
    @Override
    public void run(){
        System.out.println("new Thread!");
    }

    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

2. 实现Runnable接口

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

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();
        new Thread(runnable).start();
    }
}

由于java是单继承多实现的,所以实现Runnable接口比继承Thread类更好一点

3. 使用lambda表达式

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

4. 使用线程池

public class ThreadPool {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(()->{
            System.out.println("new Thread");
        });
        service.shutdown();
    }
}

5. 实现Callable接口

public class MyCall implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("new Thread");
        return "success";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建线程池
        ExecutorService service = Executors.newCachedThreadPool();
        //创建线程
        Future<String> submit = service.submit(new MyCall());
        //获得返回值
        String s = submit.get();
        System.out.println(submit);
        service.shutdown();
    }
}

不使用线程池的方式

public class MyCall implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("new Thread");
        return "success";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new MyCall());
        Thread thread = new Thread(futureTask);
        thread.start();
        System.out.println(futureTask.get());
    }
}