Recently done projects use the third-party push feature, and then create a thread to loop through the data in the queue, and the thread pauses for 2 seconds when the queue is empty. Everything is as spicy as you can imagine. But in the back of the test found that the push of the message, and then found that the original push thread due to throw an exception directly hanging, Then Baidu a solution, thank the predecessors for us to point out the direction. found that using the Observer pattern in Java can be a good solution to this problem, the following is the test code I wrote ...
The first is a thread class that inherits observable implementation runnable, noting the code in the catch:
PackageCom.lifesense;Importjava.util.Observable;Importjava.util.concurrent.BrokenBarrierException; Public classPushservieextendsObservableImplementsRunnable {//once this method is called, the Observer can be notified immediately, in this case the listener thread Public voiddobusiness () {if(true) { Super. setchanged (); } notifyobservers (); } @Override Public voidrun () { while(true) {System.out.println ("Thread has run"); Try{Thread.Sleep (1000); if(1 = = 1) { Throw NewRuntimeException ("Thread Hangs up"); } } Catch(Exception e) {e.printstacktrace (); Dobusiness (); Break; } } } Public Static voidMain (string[] args) {Pushservie ps=NewPushservie (); Listener Listener=NewListener (); Ps.addobserver (listener); NewThread (PS). Start (); }}
The following is a class that listens on this thread, as long as the Observer interface is implemented:
PackageCom.lifesense;Importjava.util.Observable;ImportJava.util.Observer; Public classListenerImplementsObserver {@Override Public voidUpdate (Observable o, Object Arg) {System.out.println ("Runthread Crash"); Pushservie Run=NewPushservie (); Run.addobserver ( This); NewThread (Run). Start (); System.out.println ("Runthread Restart"); }}
Run the Main method result:
I belong to a rookie, if you find what is wrong to welcome criticism, my qq:821196632, welcome to add my QQ joint learning.
About the Java thread unexpectedly quits automatic restart: