In the Java Concurrency Programming practice, 4.4 mentions the method of locking the client. This is a validation example, but it is not good to write, but you can see the result.
Packagecom.blackbread.test;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classGoodlisthelper<e> { Publiclist<e> list = Collections.synchronizedlist (NewArraylist<e>()); Public BooleanPutifabsent (E x)throwsinterruptedexception {synchronized(list) {BooleanAbsent =!list.contains (x); if(absent) {if(List.contains (x)) System.out.println (List.contains (x)); List.add (x); } returnabsent; } } Public classPrintAextendsThread {PrivateGoodlisthelper<string>Goodlisthelper; PrivateString value; PublicPrintA (goodlisthelper<string>Goodlisthelper, String value) { This. Goodlisthelper =Goodlisthelper; This. Value =value; } @Override Public voidrun () {Try{goodlisthelper.putifabsent (value); } Catch(interruptedexception e) {e.printstacktrace (); } } } Public classPrintbextendsThread {PrivateGoodlisthelper<string>Goodlisthelper; PrivateString value; PublicPRINTB (goodlisthelper<string>Goodlisthelper, String value) { This. Goodlisthelper =Goodlisthelper; This. Value =value; } @Override Public voidrun () {goodListHelper.list.add (value); } } Public Static voidMain (string[] args)throwsinterruptedexception {FinalGoodlisthelper<string> Goodlisthelper =NewGoodlisthelper<string>(); NewThread (NewRunnable () {@Override Public voidrun () {Executorservice executor= Executors.newfixedthreadpool (50); for(inti = 0; i < 1000; i++) {Thread T= Goodlisthelper.NewPrintA (Goodlisthelper, string.valueof (i)); Executor.execute (t); } executor.shutdown (); }}). Start (); NewThread (NewRunnable () {@Override Public voidrun () {Executorservice executor= Executors.newfixedthreadpool (50); for(inti = 0; i < 1000; i++) {Thread T= Goodlisthelper.NewPrintb (Goodlisthelper, string.valueof (i)); Executor.execute (t); } executor.shutdown (); }}). Start (); }}
Read Java concurrency Programming practice, adding functionality to a thread-safe class-Client Lock Implementation Example