当前位置: 移动技术网 > IT编程>开发语言>Java > 死磕 java线程系列之创建线程的8种方式

死磕 java线程系列之创建线程的8种方式

2019年10月07日  | 移动技术网IT编程  | 我要评论
(手机横屏看源码更方便) 问题 (1)创建线程有哪几种方式? (2)它们分别有什么运用场景? 简介 创建线程,是多线程编程中最基本的操作,彤哥总结了一下,大概有8种创建线程的方式,你知道吗? 继承Thread类并重写run()方法 继承Thread类并重写run()方法,这种方式的弊端是一个类只能继 ...

(手机横屏看源码更方便)


问题

(1)创建线程有哪几种方式?

(2)它们分别有什么运用场景?

简介

创建线程,是多线程编程中最基本的操作,彤哥总结了一下,大概有8种创建线程的方式,你知道吗?

继承thread类并重写run()方法

public class creatingthread01 extends thread {

    @override
    public void run() {
        system.out.println(getname() + " is running");
    }

    public static void main(string[] args) {
        new creatingthread01().start();
        new creatingthread01().start();
        new creatingthread01().start();
        new creatingthread01().start();
    }
}

继承thread类并重写run()方法,这种方式的弊端是一个类只能继承一个父类,如果这个类本身已经继承了其它类,就不能使用这种方式了。

实现runnable接口

public class creatingthread02 implements runnable {
    @override
    public void run() {
        system.out.println(thread.currentthread().getname() + " is running");
    }

    public static void main(string[] args) {
        new thread(new creatingthread02()).start();
        new thread(new creatingthread02()).start();
        new thread(new creatingthread02()).start();
        new thread(new creatingthread02()).start();
    }
}

实现runnable接口,这种方式的好处是一个类可以实现多个接口,不影响其继承体系。

匿名内部类

public class creatingthread03 {
    public static void main(string[] args) {
        // thread匿名类,重写thread的run()方法
        new thread() {
            @override
            public void run() {
                system.out.println(getname() + " is running");
            }
        }.start();

        // runnable匿名类,实现其run()方法
        new thread(new runnable() {
            @override
            public void run() {
                system.out.println(thread.currentthread().getname() + " is running");
            }
        }).start();
        
        // 同上,使用lambda表达式函数式编程
        new thread(()->{
            system.out.println(thread.currentthread().getname() + " is running");
        }).start();
    }
}

使用匿名类的方式,一是重写thread的run()方法,二是传入runnable的匿名类,三是使用lambda方式,现在一般使用第三种(java8+),简单快捷。

实现callabe接口

public class creatingthread04 implements callable<long> {
    @override
    public long call() throws exception {
        thread.sleep(2000);
        system.out.println(thread.currentthread().getid() + " is running");
        return thread.currentthread().getid();
    }

    public static void main(string[] args) throws executionexception, interruptedexception {
        futuretask<long> task = new futuretask<>(new creatingthread04());
        new thread(task).start();
        system.out.println("等待完成任务");
        long result = task.get();
        system.out.println("任务结果:" + result);
    }
}

实现callabe接口,可以获取线程执行的结果,futuretask实际上实现了runnable接口。

定时器(java.util.timer)

public class creatingthread05 {
    public static void main(string[] args) {
        timer timer = new timer();
        // 每隔1秒执行一次
        timer.schedule(new timertask() {
            @override
            public void run() {
                system.out.println(thread.currentthread().getname() + " is running");
            }
        }, 0 , 1000);
    }
}

使用定时器java.util.timer可以快速地实现定时任务,timertask实际上实现了runnable接口。

线程池

public class creatingthread06 {
    public static void main(string[] args) {
        executorservice threadpool = executors.newfixedthreadpool(5);
        for (int i = 0; i < 100; i++) {
            threadpool.execute(()-> system.out.println(thread.currentthread().getname() + " is running"));
        }
    }
}

使用线程池的方式,可以复用线程,节约系统资源。

并行计算(java8+)

public class creatingthread07 {

    public static void main(string[] args) {
        list<integer> list = arrays.aslist(1, 2, 3, 4, 5);
        // 串行,打印结果为12345
        list.stream().foreach(system.out::print);
        system.out.println();
        // 并行,打印结果随机,比如35214
        list.parallelstream().foreach(system.out::print);
    }
}

使用并行计算的方式,可以提高程序运行的效率,多线程并行执行。

spring异步方法

首先,springboot启动类加上@enableasync注解(@enableasync是spring支持的,这里方便举例使用springboot)。

@springbootapplication
@enableasync
public class application {
    public static void main(string[] args) {
        springapplication.run(application.class, args);
    }
}

其次,方法加上@async注解。

@service
public class creatingthread08service {

    @async
    public void call() {
        system.out.println(thread.currentthread().getname() + " is running");
    }
}

然后,测试用例直接跟使用一般的service方法一模一样。

@runwith(springrunner.class)
@springboottest(classes = application.class)
public class creatingthread08test {

    @autowired
    private creatingthread08service creatingthread08service;

    @test
    public void test() {
        creatingthread08service.call();
        creatingthread08service.call();
        creatingthread08service.call();
        creatingthread08service.call();
    }
}

运行结果如下:

task-3 is running
task-2 is running
task-1 is running
task-4 is running

可以看到每次执行方法时使用的线程都不一样。

使用spring异步方法的方式,可以说是相当地方便,适用于前后逻辑不相关联的适合用异步调用的一些方法,比如发送短信的功能。

总结

(1)继承thread类并重写run()方法;

(2)实现runnable接口;

(3)匿名内部类;

(4)实现callabe接口;

(5)定时器(java.util.timer);

(6)线程池;

(7)并行计算(java8+);

(8)spring异步方法;

彩蛋

上面介绍了那么多创建线程的方式,其实本质上就两种,一种是继承thread类并重写其run()方法,一种是实现runnable接口的run()方法,那么它们之间到底有什么联系呢?

请看下面的例子,同时继承thread并实现runnable接口,应该输出什么呢?

public class creatingthread09 {

    public static void main(string[] args) {
        new thread(()-> {
            system.out.println("runnable: " + thread.currentthread().getname());
        }) {
            @override
            public void run() {
                system.out.println("thread: " + getname());
            }
        }.start();
    }
}

说到这里,我们有必要看一下thread类的源码:

public class thread implements runnable {
    // thread维护了一个runnable的实例
    private runnable target;
    
    public thread() {
        init(null, null, "thread-" + nextthreadnum(), 0);
    }
    
    public thread(runnable target) {
        init(null, target, "thread-" + nextthreadnum(), 0);
    }
    
    private void init(threadgroup g, runnable target, string name,
                      long stacksize, accesscontrolcontext acc,
                      boolean inheritthreadlocals) {
        // ...
        // 构造方法传进来的runnable会赋值给target
        this.target = target;
        // ...
    }
    
    @override
    public void run() {
        // thread默认的run()方法,如果target不为空,会执行target的run()方法
        if (target != null) {
            target.run();
        }
    }
}

看到这里是不是豁然开朗呢?既然上面的例子同时继承thread并实现了runnable接口,根据源码,实际上相当于重写了thread的run()方法,在thread的run()方法时实际上跟target都没有关系了。

所以,上面的例子输出结果为thread: thread-0,只输出重写thread的run()方法中的内容。


欢迎关注我的公众号“彤哥读源码”,查看更多源码系列文章, 与彤哥一起畅游源码的海洋。

qrcode

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网