下文笔者讲述java中实现异步多线程的简介说明,如下所示
写在前面的话:
以前我们执行异步多任务,采用下面的代码
new Thread (new Runnable(){
public void run(){
//异步逻辑
}
}).start
//但是这么写有一个缺点:
1.new Thread 新建线程时,性能很差
2.线程缺乏统一管理,可能无限制新建线程,相互之间竞争,及可能占用过多系统资源导致死机或oom资源耗尽。
3.此种创建线程方式:如定时执行、定期执行、线程中断
那么如何提升线程的操作方式
package com.java265.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<8 ; 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.java265.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 ";
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


