(十二)你能说出四种创建线程的方式吗?

159 阅读1分钟

微信搜索《Java鱼仔》,每天一个知识点不错过

(一)每天一个知识点

你能说出四种创建线程的方式吗?

(二)回答

Java中创建线程的方式主要有四种:

1.继承Thread类实现run方法

2.实现Runable接口实现run方法

3.实现Callable接口实现call方法

4.使用线程池实现

(一)继承Thread类实现run方法

直接上代码,继承Thread类,并重写run方法,在main方法中启动线程。

public class MyThread1 extends Thread{
    public MyThread1() {
    }
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
    public static void main(String[] args) {
        MyThread1 myThread1=new MyThread1();
        myThread1.start();
    }
}

(二)实现Runable接口实现run方法

实现Runable接口,并实现run方法,在main方法中启动线程。

public class Mythread2 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }

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

(三)实现Callable接口实现call方法

实现Callable接口,并实现call方法,在main方法中启动线程。Callable接口有返回值,可通过FutureTask.get方法获取,具体实现看代码。

public class Mythread3 implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return "success";
    }

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

(四)使用线程池实现

这里我使用最简单的单例线程池来做演示,想要了解更多关于线程池的知识可以看我的往期博客

面试官:不会真有人不知道什么是线程池吧?

public class Mythread4 {
    public static void main(String[] args) {
        ExecutorService executors=Executors.newSingleThreadExecutor();
        executors.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });
        executors.shutdown();
    }
}