java 多线程,及获取线程执行结果

Thread、Runnable 创建多线程

 new Thread(new Runnable() {
           public void run() {
               System.out.println("hello");
           }
 }).start();


FutureTask 获取线程执行结果

FutureTask futureTask = new FutureTask(new Callable() {
	public Object call() throws Exception {
	    return "hello";
	}
});
new Thread(futureTask).start();
String res = (String)futureTask.get();// block

ExecutorService 更简便的获取线程执行结果方式

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(new Callable<String>() {
	public String call() throws Exception {
	    return "hello";
	}
});
String res = future.get();    

ThreadPoolExecutor 线程池

多线程缺点:频繁创建、销毁线程

线程池:封装任务,加入线程池执行,线程可重复使用。

// 多线程
for (int i=0; i<5; i++) {
	new Thread(new Runnable() {
	    public void run() {
	        System.out.println("hello ");
	    }
	}).start();
}
// 自定义线程池
public static ThreadPoolExecutor getThreadPool(int queueSize, int multi) {
    int cpuNum = Runtime.getRuntime().availableProcessors();
    queueSize = queueSize == 0 ? cpuNum*10 : queueSize;
    ArrayBlockingQueue jobs = new ArrayBlockingQueue(queueSize);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(cpuNum*multi, cpuNum*5, 5, TimeUnit.SECONDS, jobs);

    executor.allowCoreThreadTimeOut(true);// will shutdown if no task arrive within the keep-alive time
    return executor;
}

jdk 自带的 Executors 类封装了一些常用线程池,方便快速创建。

输入图片说明

Executor框架包括:线程池,Executor,Executors,ExecutorService,CompletionService,Future,Callable等。

ps:

多线程和 CountDownLatch 使用。

jdk 自带工具 jconsole 可查看 vm 状态。

int taskNum = 20;
final CountDownLatch latch = new CountDownLatch(taskNum);// 初始化任务总数
for (int i=0; i<taskNum; i++) {
    final int tmp = i;
    new Thread(new Runnable() {
        public void run() {
            System.out.println("hello "+tmp);
            latch.countDown();// 完成一个任务,计数器减一
        }
    }).start();
}

try {
    latch.await();// 阻塞到所有任务完成
    System.out.println("finish...");
} catch (InterruptedException e) {
    e.printStackTrace();
}

jdk 8 中 CompletableFuture 可以实现异步回调,而不是 Future 的阻塞、轮询。

http://www.tuicool.com/articles/UVrMNrN

参考:

http://blog.csdn.net/ns_code/article/details/17465497

http://blog.csdn.net/ghsau/article/details/7451464

转载于:https://my.oschina.net/u/2502289/blog/812751

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值