本文共 2515 字,大约阅读时间需要 8 分钟。
通过Executor来管理线程,包括了启动线程和关闭线程等。通过java.util.concurrent.ExecutorService
对象来启动线程并执行任务,因为java.util.concurrent.ExecutorService的execute方法参数类型是Runnable类的实例。比采用Thread的start()来启动线程会比较好。
1.Executor简单的实现线程:
//线程数 ExecutorService threadPool=Executors.newFixedThreadPool(3); for (int i = 0; i < 20; i++) { Runnable runnable=new Runnable() { @Override public void run() { System.out.println("启动线程=="+Thread.currentThread().getName()); } }; //放进任务 threadPool.execute(runnable); } // 关闭启动线程 threadPool.shutdown();
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(){ @Override public Thread newThread(Runnable r) { Thread thread=new Thread(r); Channel channel = connectManage.createChannel();//新建一个通道 if(channel!=null) channelManager.put(thread, channel);//一个线程对应一个通道 return thread; } });
执行线程并发送消息到相应的通道里。代码实现如下:
Runnable runnable=new Runnable() { @Override public 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{ /** * 设置处理器(用于注释处理) */ @Override public void setProcessors(Iterable processors) { // } /** * 设置格式化诊断和其他本地化数据时要应用的语言环境 */ @Override public void setLocale(Locale locale) { } /** * 执行此编译任务。编译只能被执行一次 */ @Override public Boolean call() { System.out.println(Thread.currentThread().getName()); return true; }
Future说明:future=threadPool.submit(new Task()); System.out.println(future.get()); // 关闭启动线程 threadPool.shutdown();
java.util.concurrent.ExecutorService的submit,参数类型是Runnable类型,实现具体的任务,然后这个任务执行是否成功,我们可以通过返回值进行判断,方便我们管理。
总结:JAVA Executor实现并发线程,比采用Thread的start()来启动线程会比较好。
转载地址:http://cpmqb.baihongyu.com/