创建线程的方法

创建线程的3种方法

Thread

Thread t1 = new Thread("t1") {
    @Override
    public void run() {
        log.debug("running...");
    }
};
t1.start();

Runnable

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        log.debug("running...");
    }
};
Thread t2 = new Thread(runnable, "t2");
t2.start();

FutureTask

FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
    @Override
    public Integer call() throws Exception {
        log.debug("running...");
        return 100;
    }
});
Thread t3 = new Thread(futureTask, "t3");
t3.start();

try {
    log.debug("返回值: {}", futureTask.get());
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}

完整代码

package com.byteframework.learn.thread;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


/**
 * 创建线程的3中方法
 *
 * @author sa
 * @date 2022-03-24
 */
public class CreateThread {
    private final static Logger log = LoggerFactory.getLogger(CreateThread.class);

    /**
     * 使用 Thread
     */
    private static void thread1() {
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                log.debug("running...");
            }
        };
        t1.start();
    }


    /**
     * 使用 Runnable
     */
    private static void thread2() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                log.debug("running...");
            }
        };
        Thread t2 = new Thread(runnable, "t2");
        t2.start();
    }


    /**
     * 使用 FutureTask
     * FutureTask 能够接收 Callable 类型的参数,用来处理有返回结果的情况
     */
    private static void thread3() {
        FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                log.debug("running...");
                return 100;
            }
        });
        Thread t3 = new Thread(futureTask, "t3");
        t3.start();

        try {
            log.debug("返回值: {}", futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        thread1();
        thread2();
        thread3();
    }

}
posted on 2024-12-23 15:05  屋蓝  阅读(6)  评论(0)    收藏  举报