JAVA Executor实现并发线程

来源:互联网 发布:win7禁止软件自动更新 编辑:程序博客网 时间:2024/05/16 16:15

   通过Executor来管理线程,包括了启动线程和关闭线程等。通过java.util.concurrent.ExecutorService

对象来启动线程并执行任务,因为java.util.concurrent.ExecutorService的execute方法参数类型是Runnable类的实例。比采用Threadstart()来启动线程会比较好。

  1.Executor简单的实现线程:

   

   //线程数 ExecutorService threadPool=Executors.newFixedThreadPool(3);      for (int i = 0; i < 20; i++) {   Runnable runnable=new Runnable() {@Overridepublic void run() { System.out.println("启动线程=="+Thread.currentThread().getName());}   };   //放进任务         threadPool.execute(runnable);            }// 关闭启动线程  threadPool.shutdown();

说明:
    1).通过java.util.concurrent.Executors实现线程管理工具,有3种类型 

        ExecutorService executorService = Executors.newCachedThreadPool();

        ExecutorService executorService = Executors.newFixedThreadPool(threadPoolNum);

        ExecutorService executorService = Executors.newSingleThreadExecutor();

   2).java.util.concurrent.ExecutorService的execute把任务添加到线程池里执行。

     3).java.util.concurrent.ExecutorService shutdown();关闭已经启动的线程。


 2.我们要让线程执行针对的业务,好比如有好几个通道,一个线程对应一个通道,来发送相应的信息。

   先把线程和通道对应起来,放在容器里,代码实现:

  threadPool=Executors.newFixedThreadPool(threadPoolNum, new ThreadFactory(){@Overridepublic Thread newThread(Runnable r) {Thread thread=new Thread(r);Channel channel = connectManage.createChannel();//新建一个通道if(channel!=null)channelManager.put(thread, channel);//<span style="color: rgb(85, 85, 85); font-family: 'Times New Roman';font-size:18px; line-height: 28px; ">一个线程对应一个通道</span>return thread;}});
    执行线程并发送消息到相应的通道里。代码实现如下:

   Runnable runnable=new Runnable() {@Overridepublic void run() {Thread thread=Thread.currentThread();//获取当前线程Channel channel=channelManager.get(thread);//取出线程对应的通道try {channel.basicPublish(msg.getExchange(),msg.getRouteKey(),MessageProperties.  PERSISTENT_TEXT_PLAIN,msg.getSerialBytes());//发送消息} catch (IOException e) {e.printStackTrace();}}};threadPool.execute(runnable);//添加任务


   3.我们可以获取线程执行有结果是TRUE还是FALSE。具体实现:

     

public class Task implements CompilationTask{/** * 设置处理器(用于注释处理) */@Overridepublic void setProcessors(Iterable<? extends Processor> processors) {//    }/** * 设置格式化诊断和其他本地化数据时要应用的语言环境 */@Overridepublic void setLocale(Locale locale) {}    /**     * 执行此编译任务。编译只能被执行一次     */@Overridepublic Boolean call() {System.out.println(Thread.currentThread().getName());return true;}
  Future<Boolean> future=threadPool.submit(new Task()); System.out.println(future.get()); // 关闭启动线程  threadPool.shutdown();
说明:

   java.util.concurrent.ExecutorService的submit,参数类型是Runnable类型,实现具体的任务,然后这个任务执行是否成功,我们可以通过返回值进行判断,方便我们管理。


总结:

     JAVA  Executor实现并发线程,比采用Threadstart()来启动线程会比较好。



  
  











0 0
原创粉丝点击