




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
publicclassQueryIdActionpublicvoidexecute(Contextcontext)trytrylongid=}(InterruptedException{}}}//执行方publicclassExecutionTaskimplementsRunnableprivateQueryNameActionqueryNameAction=newprivateQueryIdActionqueryIdAction=newpublicvoidrun()finalContextcontext=newSystem.out.println("ThenamequerySystem.out.println("TheidquerySystem.out.println("TheNameis"+context.getName()"and}}publicstaticvoidmain(String[]args)72
IntStream.range(1,5).forEach(i->newThread(newContextTest().new}执行结果代ThenamequeryThenamequeryThenamequeryThenamequeryTheidqueryTheidqueryTheidqueryTheidqueryTheNameisThread-1andidTheNameisThread-2andidTheNameisThread-3andidTheNameisThread-0andid然而这种方式太笨拙了,每次调用方法时,都需要传入Context为参数,而且影响一些除了以上这些方法,其实我们还可以使用ThreadLocal实现上下文。ThreadLocal是线程本地变量,可以实现多线程的数据。ThreadLocal为每一个使用该变量的线程都提供一份独立的副本,线程间的数据是的,每一个线程只能各自内部的副本变量。ThreadLocal中有三个常用的方法:set、get、initialValue,我们可以通过以下一个简单的例子来看看ThreadLocal的使用:代privatevoidtestThreadLocal()Threadt=newThread()ThreadLocal<String>mStringThreadLocal=new4publicvoidrun() 14接下来,我们使用ThreadLocal来重新实现最开始的上下文设计。你会发现,我们在两个方法中并没有通过变量来传下文,只是通过ThreadLocal获取了当前线程的上下文信代publicclassContextTest//上下文publicstaticclassContextprivateStringprivatelong6publiclonggetId()return publicvoidsetId(longid) this.id= publicStringgetName() return publicvoidsetName(Stringname) = //上下文到ThreadLocal publicfinalstaticclassActionContext privatestaticfinalThreadLocal<Context>threadLocal=new protectedContextinitialValue() returnnew publicstaticActionContextgetActionContext() return publicContextgetContext() return //获取ActionContext单 publicstaticclassContextHolder privatefinalstaticActionContextactionContext=new //设置上下文名publicclassQueryNameActionpublicvoidexecute()tryStringname= }catch(InterruptedExceptione) //设置上下文publicclassQueryIdActionpublicvoidexecute()trylongid=}catch(InterruptedExceptione) //执行方publicclassExecutionTaskimplementsRunnableprivateQueryNameActionqueryNameAction=newprivateQueryIdActionqueryIdAction=new publicvoidrun() queryNameAction.execute();// System.out.println("Thenamequery queryIdAction.execute();//设置线程 System.out.println("Theidquery System.out.println("TheNameis"+ publicstaticvoidmain(String[]args)IntStream.range(1,5).forEach(i->newThread(newContextTest().new 93运行结果代ThenamequeryThenamequeryThenamequeryThenamequeryTheidqueryTheidqueryTheidqueryTheidqueryTheNameisThread-2andidTheNameisThread-0andidTheNameisThread-1andidTheNameisThread-3andidThread-Per-Message设计模式翻译过来的意思就是每个消息一个线程的意思。例如,我们在处理Socket通信的时候,通常是一个线程处理以及I/O读写,如果I/O读这个时候Thread-Per-Message模式就可以很好地解决这个问题,一个线程I/O事件,每当到一个I/O,则交给另一个处理线程执行I/O操作。下面,我们还是通代//IO处publicclassServerHandlerimplementsprivateSocket4publicServerHandler(Socketsocket)this.socket= 8publicvoidrun()BufferedReaderin=PrintWriterout=Stringmsg=tryin=newBufferedReader(newout=newwhile((msg=in.readLine())!=null&&msg.length()!=0){//当连接成功后在System.out.println("serverreceived:"+ }catch(Exceptione)}finallytry}catch(IOExceptione) try}catch(Exceptione) try}catch(IOExceptione) 41代//SocketpublicclassServer3privatestaticintDEFAULT_PORT=privatestaticServerSocket6publicstaticvoidstart()throwsIOException publicstaticvoidstart(intport)throwsIOExceptionif(server!=null) try //启动服 server=new //通过无线循环客户端连 while(true) Socketsocket= //当有新的客户端接入时,会执行下 longstart= newThread(new longend= }finally
System.out.println("Spendtimeis"+(end-
if(server!=null)System.out.println服务器已关闭。");}} publicstaticvoidmain(String[]args)throws//运行服务newThread(new{publicvoidrun()try}catch(IOExceptione)}}}}以上,我们是完成了一个使用Thread-Per-Message计模式实现的Socket务端的代使用这种设计模式,如果遇到大的高并发,就会出现严重的性能问题。如果针对每个I/O请求都创建一个线程来处理,在有大量请求同时进来时,就会创建大量线程,而此时JVM这里的Worker是工人的意思,代表在WorkerThread设计模式中,会有一些工人(线来。除了工人角色,WorkerThread设计模式中还包括了流水线和产品。这种设计模式相比Thread-Per-Message计模式,可以减少频繁创建、销毁线程所带来我们可以假设一个场景来看下该模式的实现,通过WorkerThread计模式来完成一个物假设一个物流仓库的物流分拣流水线上有8个机器人,它们不断从流水线上获取包裹并对代//publicclassPackageprivateStringprivateString5publicStringgetName()return 9publicvoidsetName(Stringname)= publicStringgetAddress()return publicvoidsetAddress(Stringaddress)this.address= publicvoidexecute()System.out.println(Thread.currentThread().getName()+"executed 25//3finalstaticint3finalstaticintMAX_PACKAGE_NUM=45finalPackage[]6finalWorker[]7int8int9intPackageChannel(intworkers)this.packageQueue=newthis.head=this.tail=this.count=this.workerPool=new}voidinit()for(inti=0;i<workerPool.length;i++){workerPool[i]=newWorker("Worker-"+i,}}*switchtostartallofworkertovoidstartWorker()}synchronizedvoidput(Packagepackagereq)while(count>=packageQueue.length)try}catch(InterruptedExceptione)}}this.packageQueue[tail]=this.tail=(tail+1)%}synchronizedPackagetake()while(count<=0)try
代 }catch(InterruptedExceptione)
}Packagerequest=this.head=(this.head+1)%this.count--return}}代//publicclassWorkerextendsprivatestaticfinalRandomrandom=newprivatefinalPackageChannel5 publicWorker(Stringname,PackageChannelchannel)78this.channel=9}publicvoidrun()while(true)try}catch(InterruptedExceptione)}}}}代publicclassTestpublicstaticvoidmain(String[]args)//新建8finalPackageChannelchannel=new//开始工78915
//为流水线添加for(inti=0;i<100;i++)Packagepackagereq=newPackage();}}我们可以看到,这里有8个工人在不断地分拣仓库中已经包装好的商读写分离的业务场景中,则经常会用到ThreadLocal实现动态切换数据源操作。但在使用ThreadLocal时,我们需要注意内存泄漏问题,在之前的第25讲中,我们已经讨论过这个当主线程处理每次请求都非常耗时时,就可能出现阻塞问题,这时候我们可以考虑将主线程业务分工到新的业务线程中,从而提高系统的并行处理能力。而Threa-Per-Message设计模式
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025-2030中国胡椒基丙酮市场供需形势分析及前景营销渠道研究报告
- 2025-2030中国聚酯捆绑带行业市场现状供需分析及投资评估规划分析研究报告
- 2025-2030中国聚合亚甲基二苯基二异氰酸酯(聚合MDI)行业市场发展趋势与前景展望战略研究报告
- 2025-2030中国耐热玻璃器皿行业市场现状供需分析及投资评估规划分析研究报告
- 2025-2030中国老人奶粉市场消费前景及未来供需规模预测研究报告
- 2025-2030中国美罗培南行业发展分析及发展前景与投资研究报告
- 2025-2030中国网销基金行业市场现状分析及竞争格局与投资发展研究报告
- 2025-2030中国绿化苗木行业营销模式分析与未来供需规模调研报告
- 2025-2030中国绣花坯布行业市场发展分析及前景趋势与投资研究报告
- 2025-2030中国线性Α-烯烃市场现状调查及发展态势展望研究报告
- JT-T-795-2011事故汽车修复技术规范
- 天麻栽培技术课件
- 柳公权玄秘塔碑(高清打印版字帖)
- 智能家居控制系统设计开题报告
- 冬天的艺术-完整版PPT
- 中国传统七夕节牛郎织女浪漫汇 课件(共31张ppt) 传统文化
- 部编版八年级历史(下)全册教案
- 泌尿外科手术配合-ppt课件
- YSJ 007-1990 有色金属选矿厂 试验室、化验室及技术检查站工艺设计标准(试行)(附条文说明)
- 丽声英语百科分级读物第一级Legs课件
- 核电站仪表与控制:第4章-核电厂过程参数监测仪表课件
评论
0/150
提交评论