Java concurrent programming notes 1-three ways to create threads in detail

The original course B station address: comprehensive and in-depth study of java concurrent programming, intermediate programmers will definitely advance

There are three ways to create a thread in java

The first

Create directly using new Thread ()
/**
 * 第一种创建线程方法
 * 最基础的创建线程方法
 * */
@Slf4j(topic = "c.Test1")
public class Test1 {
    public static void main(String[] args) {
    //t1是线程的名字
        Thread t = new Thread("t1"){
            @Override
            public void run() {
                log.debug("running");
            }
        };

        t.start();

        log.debug("running");
    }
}

The second

Use the Runnable interface to separate and decouple the task code from the thread. It is recommended to use
/**
 * 第二种创建线程方法
 * 使用Runnable创建线程,使得线程和任务代码分开,降低耦合
 * 推荐使用
 * 容易与线程池等高级API配合
 * 让任务类脱离Thread继承关系
 * */
@Slf4j(topic = "c.Test2")
public class Test2 {
    public static void main(String[] args) {
        /**
         * 查看源码可以发现,Runnable接口被 @FunctionalInterface 注释修饰
         * 当接口内只有一个抽象方法的时候,可以使用lambda表达式精简代码
         * */

        Runnable r = () ->{
            log.debug("running");
            log.debug("hello world");
        };


//不使用lambda表达式
//        Runnable r = new Runnable() {
//            public void run() {
//                log.debug("running");
//            }
//        };

        Thread t = new Thread(r,"t2");
        t.start();
    }
}

The third

Use FutureTask with Thread

Looking at the source code, we can see that the FutureTask class implements the RunnableFuture interface, and the RunnableFuture interface inherits from Runnable and Future. Not only can it be passed as a parameter to Thread, but also FutureTask can accept Callable type parameters, so it can return results, so it can be seen Upgraded version of Runnable.
Insert picture description here
Insert picture description here
Insert picture description here

/**
 * 第三种创建线程的方法
 * FutureTask配合Thread
 * Future能够接受Callable类型的参数,用来处理有返回结果的情况
 *
 * */
@Slf4j(topic = "c.Test3")
public class Test3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //任务对象
        FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("running");
                Thread.sleep(1000);
                return 100;
            }
        });

        Thread t = new Thread(task,"t1");
        t.start();
        //等待线程返回结果
        log.debug("{}",task.get());
    }
}
Published 42 original articles · Like 112 · Visits 10,000+

Guess you like

Origin blog.csdn.net/baidu_41860619/article/details/105587653