Java多线程之 使用ThreadPoolExecutor来创建线程

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

以前我们创建线程的时候都是主动的new一个Thread,然后调用他们的start方法,但是如果线程非常多,任务也非

常多的时候,这样写就会显得非常麻烦,当然可能效率也不是很高,Java给我们提供了叫线程创建器这个样概念的类,

他可以帮助我们管理这些线程,你做的就是编写好代码,然后交给他,她就会自动帮你运行。

当然,带cache的threadpool 对于死掉的线程重新调用,在性能上也会有非常好的表现,但是不能将太多的线程交

给他管理,否则就会把系统拖垮,下面我们来做一个例子。

package com.bird.concursey.charpet6;import java.util.Date;import java.util.concurrent.TimeUnit;public class Task implements Runnable // store the creation date of the task private Date initDate; // store the name of the task private String name; public Task(String name) {  this.initDate = new Date();  this.name = name; } @Override public void run() {  System.out.printf("%s: Task %s: Created on: %s\n", Thread    .currentThread().getName(), name, initDate);  System.out.printf("%s: Task %s: Started on: %s\n", Thread    .currentThread().getName(), name, new Date());  try {   Long duration = (long) (Math.random() * 10);   System.out.printf("%s: Task %s: Doing a task during %d seconds\n",     Thread.currentThread().getName(), name, duration);   TimeUnit.SECONDS.sleep(duration);  } catch (InterruptedException e) {   e.printStackTrace();  }    System.out.printf("%s: Task %s: Finished on: %s\n",Thread.    currentThread().getName(),name,new Date()); }}

package com.bird.concursey.charpet6;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;/** * execute every task it receives using an executor *  * @author bird 2014年9月23日 下午9:03:01 */public class Server private ThreadPoolExecutor executor; public Server() {  executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); } public void executeTask(Task task) {  System.out.printf("Server: A new task has arrived\n");  executor.execute(task);  System.out.printf("Server: Pool Size: %d\n", executor.getPoolSize());  System.out.printf("Server: Active Count: %d\n",    executor.getActiveCount());  System.out.printf("Server: Completed Tasks: %d\n",    executor.getCompletedTaskCount()); }  public void endServer() {  executor.shutdown(); }  public static void main(String[] args) {  Server server = new Server();  for(int i = 0; i < 100; i++) {   Task task = new Task("Task" + i);   server.executeTask(task);  }  server.endServer(); }}


扫描二维码关注公众号,回复: 4889540 查看本文章

如果有大量的线程进入,他会给每一个线程创建一个对象,这样就会令系统不堪重负,Executors提供了一种构造方

法,设置一个最大量,如果创建的线程数量超过了这个数量,Executors就不会再去创建这个线程,等待已经在线程池

里面的线程运行完了,有空闲的位置了才去继续创建新线程,这样就会让系统变的健壮。


上面的代码都不需要该,我们只需要在构造函数的地方重新实例化一个代码如下

 public Server() {  executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5); }


           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_43679366/article/details/84105446