创建线程的三种方法

extends Thread直接创建

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class Test {
    static Logger logger = LogManager.getLogger(Test.class);

    public static void main(String[] args) {

        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                logger.debug("thread name: {} {}", this.getName(), "hello juc");
            }
        };
        t1.start();
    }
}

劣势
  • 需要继承,不灵活

implements Runnable再集合Thread创建

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class Test {
    static Logger logger = LogManager.getLogger(Test.class);

    static class TestRunnable implements Runnable {

        @Override
        public void run() {
            logger.debug("thread name: {} {}", Thread.currentThread().getName(), "hello juc");
        }
    }

    public static void main(String[] args) {

        Thread t1 = new Thread(new TestRunnable(), "t2");
        t1.start();
    }
}

优势
  • 可以配合线程池相关高级API用
  • 跳出继承体系,灵活

implements Callable创建

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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


public class Test {
    static Logger logger = LogManager.getLogger(Test.class);

    static class TestCallable implements Callable<Integer> {

        @Override
        public Integer call() throws Exception {
            return 100;
        }
    }

    public static void main(String[] args) {

        FutureTask<Integer> futureTask = new FutureTask<Integer>(new TestCallable());
        Thread t3 = new Thread(futureTask, "t3");
        t3.start();
        try {
            logger.debug(futureTask.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

优势
  • 跳出继承体系,灵活

  • 有返回值

  • 可以抛出异常

劣势
  • get()方法其实有可能阻塞,需要等到线程运行完了才能拿到返回值
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值