Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement listener Mode in Java

Shulou Source: shulou.com Published: 2022-06-01 08:01:40 09月29日 Update

This article mainly introduces how Java to achieve the listener model, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Code presentation

Main: test class

ObServer: each listening object implements the interface, overrides the method, and completes its own business

Public interface ObServer {/ * when a monitored object changes * all implement the method handling methods * / void exceptionHandler ();}

Subject: listener container

Public interface Subject {/ * add the observed object * / void add (ObServer obServer); / * notify all observers to complete their own exceptionHandler method * / void notifyAllSubject ();}

SubjectHandler: the implementation class of the listener container

Public class SubjectHandler implements Subject {/ * stores the listening object * / private static final List SUBJECTS = Collections.synchronizedList (new LinkedList ()); @ Override public void add (ObServer subject) {SUBJECTS.add (subject);} @ Override public void notifyAllSubject () {SUBJECTS.forEach (ObServer::exceptionHandler);}}

Thread1, Thread2 test object

Simulate two threads to operate on the database, and if there is an exception in Threa1 execution, then terminate all threads and roll back them.

Threa1:

Public class Thread1 implements ObServer, Runnable {@ SneakyThrows @ Override public void run () {System.out.println ("thread1 run"); Thread.sleep (1000); System.out.println ("T1 end");} @ SneakyThrows @ Override public void exceptionHandler () {System.out.println ("thread1 rollback.");}}

Thread2:

Public class Thread2 implements ObServer, Runnable {private static Thread CURRENT_THREAD; private static volatile boolean FLAG = false; @ SneakyThrows @ Override public void run () {CURRENT_THREAD = Thread.currentThread (); System.out.println ("thread2 running"); int count = 0; while (! FLAG) {System.out.println (count); count++ } System.out.println ("thread2 end");} @ SneakyThrows @ Override public void exceptionHandler () {FLAG = true; CURRENT_THREAD.interrupt (); System.out.println ("thread2 rollback.");}}

Test Demo

Public static void main (String [] args) throws InterruptedException {/ / create a listening container Subject subject = new SubjectHandler (); Thread1 thread1 = new Thread1 (); Thread2 thread2 = new Thread2 (); subject.add (thread1); subject.add (thread2); CompletableFuture.supplyAsync ()-> {new Thread (thread1). Start () Try {Thread.sleep (10); int a = 1 / 0; / / simulated thread 1 error} catch (InterruptedException e) {e.printStackTrace ();} return true;}). Exceptionally ((error)-> {subject.notifyAllSubject (); return false }); CompletableFuture.supplyAsync (()-> {new Thread (thread2). Start (); return true;}) .exceptionally ((error)-> {subject.notifyAllSubject (); return false;}); / / main thread await Thread.sleep (60 * 1000);}

Test result

Observable (listening container) and Observer interfaces (listeners) are provided under the java.util package, and the usage is exactly the same as ours. You only need to implement the update method of Observer and add each Observer subclass to the listening container.

Note: the setChanged method of the listener container is called first when notifying all servers of the listening container

Change changed to true (default flase)

Thank you for reading this article carefully. I hope the article "how to realize the listener mode in Java" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Listening containers methods objects articles tests threads patterns interfaces observation consistency business two code value interest just at the same time subclasses data Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Microsoft MySQL Apple Shulou Information