并发_创建线程

  1. 继承Thread类, 重写run()方法, 调用start()方法启动线程.
    优点: 在run方法内获取当前线程直接使用this就可以了, 无须使用Thread.currentThred()
    缺点: ①Java不支持多继承 ②任务和代码没有分离 ③没有返回值
  2. 实现Runnable接口, 具体实现run()方法, 也没有返回值.
  3. 实现Callable接口的call()方法, 使用创建的FutureTask对象作为任务创建一个线程并启动它, 最后通过futureTask.get()等待任务执行完毕, 并返回结果.
package com.syq.demo.concurrent.create;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Description 三种创建线程的方法
 * @Author SYQ
 **/
public class CreateThread {
    public static void main(String[] args) {
        // 继承Thread
        Thread t = new MyThread();
        t.start();

        // 实现Runnable接口
        Runnable r = new RunnableTask();
        new Thread(r).start();
        new Thread(r).start();

        // 实现Callable接口, 可以返回值
        FutureTask futureTask = new FutureTask<>(new CallerTask());
        new Thread(futureTask).start();
        try {
            // 等待任务执行完毕, 并返回结果
            String result = futureTask.get();
            System.out.println(result);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("thread1 name: " + this.getName());
            System.out.println("I am a child thread, extends thread");
        }
    }

    public static class RunnableTask implements Runnable {
        @Override
        public void run() {
            System.out.println("thread2 name: " + Thread.currentThread().getName());
            System.out.println("I am a child thread, implements runnable");
        }
    }

    public static class CallerTask implements Callable {
        @Override
        public String call() throws Exception {
            System.out.println("thread3 name: " + Thread.currentThread().getName());
            return "I am a child thread, implements Callable";
        }
    }

}

你可能感兴趣的:(并发_创建线程)