Plus "Close Hook" (Shutdownhook)

xiaoxiao2021-03-18  223

registered:

Runtime.Getruntime (). Addshutdownhook (thread t);

Logout:

Runtime.Getruntime (). RemoveShutdownhook (Thread T);

[example]

/ ** * In this thread, the cleaning work before the program exits * * @Author administrator * * /

Class testthread extends thread {boolean isterminal

=

False;

public

Void Run () {

While

(! isterminal) {Try {thread.sleep

1000

);} Catch (interruptedException e) {E.PrintStackTrace ();} system.out.println ("Run Sub Thread");}}

/ ** /

/ ** * Clean up work * /

public

Void onterminal () {isterminal

=

True; System.Out.println ("Stop Sun Sub Thread");}}

/ ** /

/ ** * shutdowndownhook test class * @Author administrator * * /

public

Class Testshutdownhook Extends Thread {Testthread Testthread;

public

Void Addthread (Testthread T) {Testthread

=

T;

/ ** /

/ ** * Clean up before the program exits * /

public

Void Run () {system.out.println ("this

IS

Shutdownhook "); testthread.onterminal ();

public

Static void main (String

[]

Args) {testshutdownhook m

=

New testshutdownhook (); testthread t

=

New Testthread (); T.Start (); M.Addthread (t);

//

Registration Exit Process Thread Runtime.Getruntime (). Addshutdownhook (M);}}

operation result:

Run Sub Threadrun Sub Threadrun Sub Threadrun Sub Threadthis Is ShutdownhookStop Sun Sub Thread

It can be seen that the Testthread thread started when the program exited, and the defined release work was performed.

Ctrl C exits the program.

转载请注明原文地址:https://www.9cbs.com/read-129890.html

New Post(0)