Java异步多线程

问题:执行一个异步任务你还只是如下new Thread吗?

new Thread (new Runnable(){
    public void run(){
        //异步逻辑
    }
}).start

缺点:
1. 每次new Thread新建对象性能很差
2. 线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom资源耗尽。
3. 功能单一:如定时执行、定期执行、线程中断。

知识提升

Java5之后,并发线程发生了根本的变化,最重要的莫过于新的启动、调度、管理线程的一大堆API了。在Java5以后,通过Executor来启动线程比用Thread的start()更好。在新特征中,可以很容易控制线程的启动、执行和关闭过程,还可以很容易使用线程池的特性。当将一个任务添加到线程池中的时候,线程池会为每个任务创建一个线程,该线程会在之后的某个时刻自动执行。

package com.swagger.demo.thread;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class MyThreadPool {

    public static void main(String [] args){
        Executor executor = Executors.newFixedThreadPool(10);
        for (int i = 0 ; i<5 ; i++){
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("我是一个子线程!!");
                }
            });
        }
    }
}

在Java5之后,任务分两类:一类是实现了Runnable接口的类(Thread类也是实现了Runnable接口),一类是实现了Callable接口的类。两者都可以被ExecutorService执行,但是Runnable任务没有返回值,而Callable任务有返回值。并且Callable的call()方法只能通过ExecutorService的( task) 方法来执行,并且返回一个 ,是表示任务等待完成的 Future。

package com.swagger.demo.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallBackThread implements Callable<String> {

    public static void main(String [] args) throws Exception{
        ExecutorService executor = Executors.newFixedThreadPool(10);
        //void execute(Runnable command);
        //实现Callable接口的线程需要使用executor.submit(Callable command )
        Future<String> submit = executor.submit(new MyCallBackThread());
        System.out.println(submit.get());

    }

    @Override
    public String call() throws Exception {
        System.out.println("我是一个Callable子线程");
        return "this is Callable thread return ";
    }
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值