2024年10月javahook(java多线程时程序运行完成为什么不会自动关闭退出)

 更新时间:2024-10-12

  ⑴javahook(java多线程时程序运行完成为什么不会自动关闭退出

  ⑵java多线程时程序运行完成为什么不会自动关闭退出

  ⑶具体演示如下:viewplaincopypackagetest;publilassTestShutDownHook{publicTestShutDownHook(){doShutDownWork();}privatevoiddoShutDownWork(){Runtimerun=Runtime.getRuntime();//当前Java应用程序相关的运行时对象。run.addShutdownHook(newThread(){//注册新的虚拟机来关闭钩子Overridepublicvoidrun(){//程序结束时进行的操作System.out.println(“程序结束调用“);}});}publicstaticvoidmain(Stringargs){newTestShutDownHook();for(inti=;i《;i++){//在这里增添您需要处理代码}System.out.println(i);}}}在上述程序中,我们可以看到通过在程序中增加Runtime.getRuntime().addShutdownHook(newThread())事件监听,捕获系统退出消息到来,然后,执行我们所需要完成工作,从而使我们的程序更健壮!望采纳,谢谢。

  ⑷jdk这是什么原因造成的,输入javac,java,java-verson都会显示报错

  ⑸在JAVA中如何实现长时间任务

  ⑹摘要:在软件开发中,我们经常面临着处理长时间任务的多线程编程问题。在我们的ezOne平台的开发中就多处涉及到,如JPC数据服务JPC数据处理服务、报警联动、门禁系统等。本人在编写DEMO程序的过程中几易其稿,煞费心机,但依然感觉有许多地方需要改进,为了减少多线程编程带来的风险,我尝试翻译整理了一个类似问题的解决方案框架以达到一劳永逸。为了便于阅读,保留原文。一、问题背景Quiteoften,youneedaclasstoperformtaskslikedataprocessing,listeningtoevents,orcheckinganotherclass’activitiesduringtheapplication’slifetime.Toachievethis,youprobablyusethreadswithasetoflocksandnotifications.JavaThreadAPIiswelldocumented,butyouneedagreatdealofcodeandexperiencetomakeyourthreadworkproperlyandefficiently.Youcanavoidwritingsuchclassesfromscratcheverytimeyouneedthemandbuildamorerobustapplicationbyapplyingtheframeworkwe’lldiscussinthisarticle.在应用程序中我们经常需要一个类去完成像数据处理、监听事件或检查另一个类的活动等任务。为了达到这个目标,我们可能使用带有一套锁和消息通知的线程。JAVA线程API已经很好的文档化,但为了使线程能够正确而高效地运行,程序员仍然需要丰富的编程经验并编写大量的代码。通过应用本篇文章中讨论的框架,程序员能够避免忍受煎熬写大量的代码,快速创建健壮的应用程序。二、长时间运行任务的程序框架Frameworkforlong-runningtasksTheprimarythingaboutalong-livedtaskisthatitshouldsomehowbekeptrunningduringtheapplicationlifetime.Therightwaytoaomplishthisistoprovideathreadofexecutionforaparticulartask.Youcreateataskasathreadorasanimplementationofthejava.lang.Runnableinterface.IfyouimplementRunnable,youcangainbetterobject-orienteddesignandavoidthesingle-inheritanceproblems.YoucanalsomoreefficientlymanipulatewithRunnableinstances,forexample,usingathreadpoolthatusuallyneedsaRunnableinstance,notathread,torun.关于长时间运行的任务的主要事情是如何在应用程序的生命期使它一直保持运行。实现的恰当方法是提供一个线程来执行这个特定的任务。我们可以通过继承Thread类或实现java.lang.Runnable接口来达到该目标。如果采用实现Runnable接口的方式,就可以能够获得更好的面向对象的设计,同时可以避免JAVA中的单继承问题。另外,我们也能更有效的处理Runnable实例(例如使用线程池通常需要一个Runnable实例而不是线程来运行。TheessenceoftheframeworkistheabstractclassWorker(ListingA),whichimplementstheRunnableinterfaceandprovidesthehelpermethodsforefficienttaskhandling.Someofthemethodsarefullyimplemented,liketherun()method,butsomeareabstractandhavetobefilledbyyou.Ifyouwanttocreatealong-runningclass,youneedonlytoextendtheWorkerclassandimplementseveralabstractmethods.Let’slookatthesemethodsinmoredetail.框架的基础是一个叫Worker的抽象类,它实现了Runnable接口,并提供了有效处理任务的好方法。这些方法有些已经被实现,如run()方法,但有些是抽象方法,开发人员必须自己来实现。如果要创建一个长时间运行的类,你只需要继承Worker类并实现几个抽象方法。让我们看看这些方法的细节。Therun()methodoftheWorkerclassisdesignedtocontinuouslyexecutethework()methoduntilitisstopped.Thework()methodcanberesponsiblefordataprocessing,reactiontosomeevent,filereadingorwriting,SQLexecution,etc.Itcanthrowanexception,soitisagoodpracticetopropagateitandlettherun()methodhandleit.Worker类的run()方法被设计成只要不停止运行就持续的执行work()方法。work()方法可以负责数据处理、事件响应、文件读写、,执行SQL命令等操作。这样work()方法能够抛出异常,并将异常传给run(),然后由run()方法来处理这些异常。Therun()methodhastwolevelsoftry-catchclause:outsideandinsidethewhile-loop.Thefirsttry-catchclauseismeanttocatchallnonprogrammedexceptionsandguaranteethattherun()methodneverexits.Thesecondclausewillcatchanykindofexceptionsbelongingtobusinesslogicandbehaveaordingly.Ifsomewaitingoperationtakesplaceinthework()method(e.g.,waitingonanInputStreamoraSocket),itisadvisabletopropagateanInterruptedException.Thethingtokeepinmindisthatthework()methoddoesnotneedtohaveanywhile-looptokeepitgoingaslongasanapplicationruns.TheWorkerdoesthisforyou.run()方法有内外两层try-catch语句:一层处于while-loop循环外,一层在while-loop循环内。前一个try-catch用于捕获非编程异常以确保run()方法不退出。后一个try-catch语句捕获关于业务逻辑和相应行为的各种异常。如果在work()方法中发生了一些等待操作(例如等待一个输入流或一个Socket,抛出一个InterruptedException的方法是可取的。要记住的是只要应用程序在运行,work()方法不需要任何while-loop循环去维持它运行,这一切由Worker代办了。Whentherun()methodstarts,itcallstheprepareWorker()whichisdesignedtoprepareallresourcesneededforalong-runningtask(ListingA).Inthismethodcall,youcan,forexample,establishadatabaseconnectionoropenafilethatwillbeusedfurther.Itisespeciallygoodtoplaceheresomeblockingoperationslikeopeningasocket,becausetheywillbedoneinaseparatethreadandthuswillnotblockthemainthreadofexecution.run()开始时,调用prepareWorker()方法来准备长时间运行任务需要的所有资源(参考程序清单A。例如,在这个方法中可以打开一个将要用到的数据库连接或文件。尤其对于那些像建立一个socket这样的阻塞操作放在这儿是很好的。因为若让它们在一个独立的线程中运行,则不会阻塞主线程的执行。TheoppositeofthepreviousmethodisthereleaseWorker()whichiscalledwhentherun()methodisabouttoexit(ListingA).Here,youcanputthecodetodisposeofsystemresourcesusedbythistaskortoperformothercleanup.Thismethodissimilartojava.lang.Object.finalize(),butitisexplicitlycalledbeforeathreadterminates.与前面方法相反的是releaseWorker(),它在run()方法准备退出时被调用(参考程序清单A。在该方法中你可以编写那些释放系统资源或执行其它清除动作的代码。该方法类似于java.lang.Object.finalize(),但它在线程中止时被显式的调用。三、框架中的错误处理机制HandlingerrorsintheframeworkAnotherimportantmethodisthehandleError(),whichtakesajava.lang.Throwableasaparameter.Thismethodiscalledeachtimeanerrorsituationourswithintherun()method.Itisuptoyouhowtoimplementerrorhandling.Onewayistologerrorsandcontroltaskterminationbycallinghalt()method(ListingA).另一个重要的方法是handleError(),它带有一个java.lang.Throwable的输入参数。在run()方法每次发生错误时调用这个方法。这依赖于你怎么实现错误处理。方法之一是写错误日志并通过调用halt()方法中止任务(参考程序清单A。TheisCondition()methodisusedtotellwhetherexecutionofthework()methodcanbestarted,thusallowinggranularcontroloveratask.Itisusefulinevent-triggeredframeworkswhenexecutionofthework()methodispendinguntilsomecondition?forexample,abufferisnotempty?isfulfilled.InWorker’simplementation,theconditionischeckeduponalocknotificationandperiodicallywithatimeintervalyouspecifyinthesetTimeout()method(ListingA).Ifyoudon’tneedanywaitingblocksinatask,justmaketheisCondition()methodalwaysreturntrue.isCondition()方法用于判断work()方法是否能够被执行。因此允许细粒度地控制任务。这在事件触发的框架中非常有用。当work()方法的执行条件未满足时,work方法将被挂起,直到条件完全满足(例如,缓存区非空。在Worker的实现中这个条件将按在方法setTimeout()中指定的时间周期地检查一个锁通知。如果在任务中不需要任何等待阻塞,仅仅只要使isCondition()方法总是返回真值。四、任务终止时机WhentoterminateYou’llalsoneedtheisRunning(),broadcast(),andhalt()methods.QueryingisRunning(),youcancheckwhetherataskisstillrunningandmakeadecisionwhethertoterminateit.Thebroadcast()methodjustnotifiesthelockobjectandmakesataskproceedifithasbeenwaitingonthislock.Thehalt()methodstopsatask,sotherun()methodwillexitassoonasthenextisRunning()statusischecked.Becausethismethodnotifiesonlyonelockthatmayblockthistask’sthread,itisadvisabletousethesamelockobjectwhenyoudoblockingoperationswithinthework()method(ListingB).Ifyoucan’tusethesamelockobject,suchaswhenyou’reblockingonthejava.io.InputStream.read()method,youshouldaddexplicitnotificationofallpossiblelocksoraddjava.lang.Thread.interrupt()toyourhalt()method.Thejava.lang.Thread.interrupt()worksifanobjectyouareblockedonprocessesthissignalcorrectly.Forexample,itworksforInputStream.read()butdoesn’tworkforjava.sql.PreparedStatement.execute(),soyouhavetotesthalt()methodineachparticularsituation.你还需要isRunning(),broadcast(),halt()方法。通过访问isRunning()方法,你将能检查某个任务是否正在运行,并决定是否中止它。broadcast()方法正确地通知锁对象,并且如果这个对象一直等待这个锁,那么就激活这个任务。halt()方法中止一个任务,因此下一isRunning()状态一旦被调用,run()方法就退出,因为这个方法只通知那个可能阻塞这个任务线程的锁。当在work()方法中执行阻塞作业时用相同的锁是明智的。如果你不能用相同的锁对象时,例如在执行java.io.InputStream.read()方法遇到阻塞时,你就应该添加所有可能锁的显式通知或者增加java.lang.Thread.interrupt()到halt()中。如果一个你阻塞的对象被正确处理,java.lang.Thread.interrupt()将会起作用。例如,它在InputStream.read()执行时有作用,但在执行java.sql.PreparedStatement.execute()不起作用,因此在每个特殊的条件下你必须测试halt()方法。OnceyouarefamiliarwiththeWorkerclass,youcaneasilycreateyourownimplementation(ListingB).Torunthisclassasathread,simplyuseanewThread(newWaitedWorker()).start.ApplyingThread.interrupt()orWorker.halt()orabinationofthem,youcancontroltaskexecutionprecisely.Forexample,youcanstopallworkerswhenJVMshutsdownbyplacingcorrespondingcodeinthejava.lang.Runtime.addShutdownHook()method.一旦你熟悉Worker类,你就很容易创建你自己的实现(参考程序清单B,为了把这类当作一个线程运行,仅仅只需简单地使用newThread(newWaitedWorker()).start。应用Thread.interrupt()或Worker.halt()或它们的组合,你就可以准确的控制任务的执行。例如当JVM通过在java.lang.Runtime.addShutdownHook()方法中放相应的代码停止时,你就能停止所有的任务。四、结论ConclusionWe’veexaminedthelong-runningtaskframeworkandseenhowtocreatenewtasksbasedonitsabstractclass.Itsarchitectureisclearandflexibleandwasdesignedwithextensibilityinmind.Withthisframework,youcanavoidcreatingclassesfromscratch,andyou’llbeabletodevelopmoreefficientandreliableapplications.我们已经检查了长时间运行任务框架,并且看到怎样通过从创建一个基于它的抽象类的任务。它的构架是清晰和灵活的,并且被设计成可扩展的。用这个框架你能避免为创作类而绞尽脑汁,并且帮助你能够开发出高效、可靠的应用程序。参考文献、《》SimonBrown、《》JosephL.Weber致谢非常感谢曾一起工作的同事和为JAVA技术发展做出贡献的人们,没有他们的努力成果,我就不可能感受到JAVA语言的魅力;同时也要感谢我的上司周洪波博士和卢盛融总工程师,他们给予我许多有益的帮助。关于译者胡继锋,软件工程师,清华同方应用信息系统本部ezONE研究院研发人员。曾经从事DEPHI、VB、VC、C、PHP、ASP、Oracle等的开发,现在热衷于JAVA技术。同时对资本市场有一定的兴趣。

  ⑺如何在java中调用键盘命令

  ⑻RunTime.exec(“这里是命令“);那就首先说点Runtime类吧,他是一个与JVM运行时环境有关的类,这个类是Singleton的。我说几个自己觉得重要的地方。、Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一一个得到运行时环境的方法。、Runtime上其他大部分的方法都是实例方法,也就是说每次进行运行时调用时都要用到getRuntime方法。、Runtime中的exit方法是退出当前JVM的方法,估计也是唯一的一个吧,因为我看到System类中的exit实际上也是通过调用Runtime.exit()来退出JVM的,这里说明一下Java对Runtime返回值的一般规则(后边也提到了,代表正常退出,非代表异常中止,这只是Java的规则,在各个操作系统中总会发生一些小的混淆。、Runtime.addShutdownHook()方法可以注册一个hook在JVM执行shutdown的过程中,方法的参数只要是一个初始化过但是没有执行的Thread实例就可以。(注意,Java中的Thread都是执行过了就不值钱的哦、说到addShutdownHook这个方法就要说一下JVM运行环境是在什么情况下shutdown或者abort的。文档上是这样写的,当最后一个非精灵进程退出或者收到了一个用户中断信号、用户登出、系统shutdown、Runtime的exit方法被调用时JVM会启动shutdown的过程,在这个过程开始后,他会并行启动所有登记的shutdownhook(注意是并行启动,这就需要线程安全和防止死锁。当shutdown过程启动后,只有通过调用halt方法才能中止shutdown的过程并退出JVM。那什么时候JVM会abort退出那?首先说明一下,abort退出时JVM就是停止运行但并不一定进行shutdown。这只有JVM在遇到SIGKILL信号或者windows中止进程的信号、本地方法发生类似于访问非法地址一类的内部错误时会出现。这种情况下并不能保证shutdownhook是否被执行。

  ⑼xposed可以hook所有的java函数吗

  ⑽CydiaSubstrate是一个代码修改平台。它可以修改任何主进程的代码,不管是用Java还是C/C++(native代码编写的。而Xposed只支持HOOKapp_process中的java函数,因此CydiaSubstrate是一款强大而实用的HOOK工具。

  ⑾Substrate几个重要API介绍

  ⑿MS.hookClassLoad

  ⒀函数原型:voidhookClassLoad(Stringname,MS.ClassLoadHookhook);

  ⒁该方法实现在指定的类被加载的时候发出通知。因为一个类可以在任何时候被加载,所以Substrate提供了一个方法用来检测用户感兴趣的类何时被加载。

  ⒂java停止工作的故障模块LdSSDTHook.dll是个什么文件

  ⒃打开腾讯电脑管家找到工具箱;、打开工具箱找到“电脑诊所”、打开电脑诊所后在右上角的搜索内输入dlL找到需要修复的文件后点击一键修复或者可以点击详情查看原因并点击立即修复。

  ⒄Java中如何在windows桌面上添加鼠标监听事件

  ⒅去下载JInvoke,这是一个例子:如果网上找不到JInvoke.jar,我传了一个到网站了,NativeImport(library=“user“)publiativestaticintSetWindowsHookEx(intidHook,CallbackhookProc,inthModule,intdwThreadId);NativeImport(library=“user“)publiativestaticintUnhookWindowsHookEx(intidHook);publicstaticfinalintWH_MOUSE_LL=;staticJFrameframe;staticTextAreamouseEventArea=newTextArea();staticJButtonsetHookBtn;staticJButtonremoveHookBtn;publicMouseHook(){super(newBorderLayout());mouseEventArea.setText(“)Clickthe“SetMouseHook“button.

  ⒆“+“)Startclickinganywhereonthedesktop.Mouseclickswillbecapturedhere.

  ⒇“+“)Stopthemousehookbyclickingthe“RemoveMouseHook“button.

  ⒈“);JScrollPaneMouseEventPane=newJScrollPane(mouseEventArea);add(MouseEventPane,BorderLayout.CENTER);JPanelbuttonPanel=newJPanel();buttonPanel.setBorder(BorderFactory.createEmptyBorder(,,,));buttonPanel.setLayout(newFlowLayout(FlowLayout.RIGHT));setHookBtn=newJButton(“SetMouseHook“);setHookBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg){setMouseHook();}});removeHookBtn=newJButton(“RemoveMouseHook“);removeHookBtn.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEventarg){unsetMouseHook();}});removeHookBtn.setEnabled(false);buttonPanel.add(setHookBtn);buttonPanel.add(removeHookBtn);add(buttonPanel,BorderLayout.SOUTH);}privatevoidsetMouseHook(){setHookBtn.setEnabled(false);removeHookBtn.setEnabled(true);//Thishookiscalledinthecontextofthethreadthatinstalledit.//Thecallismadebysendingamessagetothethreadthatinstalledthehook.//Therefore,thethreadthatinstalledthehookmusthaveamessageloop.////Wecrateanewthreadaswedon’twanttheAWTEventthreadtobestuckrunningamessagepump//nordowewantthemainthreadtobestuckinrunningamessagepumpThreadhookThread=newThread(newRunnable(){publicvoidrun(){if(MouseProc.hookHandle==){inthInstance=User.GetWindowLong(Util.getWindowHandle(frame),GWL_HINSTANCE);MouseProc.hookHandle=SetWindowsHookEx(WH_MOUSE_LL,newCallback(MouseProc.class,“lowLevelMouseProc“),hInstance,);//Standardmessagedispatchloop(messagepump)Msgmsg=newMsg();while(User.GetMessage(msg,,,)){User.TranslateMessage(msg);User.DispatchMessage(msg);}}else{mouseEventArea.append(“TheHookisalreadyinstalled.

  ⒉“);}}});hookThread.start();}privatevoidunsetMouseHook(){setHookBtn.setEnabled(true);removeHookBtn.setEnabled(false);UnhookWindowsHookEx(MouseProc.hookHandle);MouseProc.hookHandle=;}privatestaticvoidcreateAndShowGUI(){//Createandsetupthewindow.frame=newJFrame(“MouseHook“);frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);MouseHookMouseEventsWindow=newMouseHook();MouseEventsWindow.setBorder(BorderFactory.createEmptyBorder(,,,));//Addcontenttothewindow.frame.add(MouseEventsWindow,BorderLayout.CENTER);//Displaythewindow.frame.pack();frame.setBounds(,,,);frame.setVisible(true);}publicstaticvoidmain(Stringargs){//Scheduleajobfortheevent-(newRunnable(){publicvoidrun(){createAndShowGUI();}});}}classMouseProc{staticinthookHandle;NativeImport(library=“user“)publiativestaticintCallNextHookEx(intidHook,intnCode,intwParam,intlParam);static{JInvoke.initialize();}publicstaticintlowLevelMouseProc(intnCode,intwParam,intlParam){if(nCode《)returnCallNextHookEx(hookHandle,nCode,wParam,lParam);if(nCode==HC_ACTION){MouseHookStructmInfo=Util.ptrToStruct(lParam,MouseHookStruct.class);Stringmessage=“Mousept:(“+mInfo.pt.x+“,“+mInfo.pt.y+“)“;switch(wParam){caseWM_LBUTTONDOWN:message+=“Leftbuttondown“;break;caseWM_LBUTTONUP:message+=“Leftbuttonup“;break;caseWM_MOUSEMOVE:message+=“Mousemoved“;break;caseWM_MOUSEWHEEL:message+=“Mousewheelrotated“;break;caseWM_RBUTTONDOWN:message+=“Rightbuttondown“;break;caseWM_RBUTTONUP:message+=“Rightbuttondown“;break;}System.out.println(message);//MouseHook.mouseEventArea.append(message+“

  ⒊“);}returnCallNextHookEx(hookHandle,nCode,wParam,lParam);}}=============================================import.jinvoke.NativeStruct;import.jinvoke.win.structs.Point;NativeStructpublilassMouseHookStruct{//MSLLHOOKSTRUCTpublicPointpt=newPoint();publicintmouseData;publicintflags;publicinttime;publicintdwExtraInfo;}

  ⒋java运行后,进程不结束,怎么办

  ⒌此种情况下是因为有线程尚未结束。一般有下面几种情况:

  ⒍什么是JavaHook

  ⒎启动计算机出现「CannotcodeJavaHook.API」--:问题:如果C:ProgramFilesTrendMicroVirusbusterJavaHook.dll档案遗失或是损坏,启动Virusbuster时会出现启计算机出现「CannotcodeJavaHook.API」请您至别台有安装Virusbuster的计算机中复制javahook.dll文件至出现问题的计算机中即可.如果计算机中Worm_klez病毒会有此现象,请先清除病毒后再重新安装Virusbuster,清除步骤:请参考如何清除Worm_Klez,PE_ELKERN解决方案:.您可将别台计算机中的javahook.dllcopy至磁盘当中.请到出问题的计算机上,按磁盘放入磁盘驱动器中.请先将Virusbuster实时监控器关闭(将鼠标移至屏幕右下角胶囊符号上,按鼠标右键选择“结束“).出现“您是否也要停止实时扫瞄“,选择“是“.将磁盘中的档案copy至C:ProgramFilesTrendMicroVirusbuster目录.重新启动计算机注:如果只有一台计算机,请重新安装Virusbuster即可

  ⒏java的API中有哪些常用的包

  ⒐ApplicationProgrammingInterface应用程序编程接口,Java的api就多的数不清了,平时编程用的都是API。

您可能感兴趣的文章:

相关文章