The first example is to learn to validate that multiple threads call the same method randomly.
PackageSyn_out_asyn;Importjava.util.ArrayList;Importjava.util.List;/*** Created by Administrator on 2017/1/19 0019.*/ Public classMyList {PrivateList List =NewArrayList (); synchronized Public voidAdd (String username) {System.out.println ("Threadname=" +thread.currentthread (). GetName () + "Add method executed"); List.add (username); System.out.println ("Threadname=" +thread.currentthread (). GetName () + "exit the Add Method"); } synchronized Public intGetSize () {System.out.println ("Threadname=" +thread.currentthread (). GetName () + "GetSize method executed"); intSizevalue=list.size (); System.out.println ("Threadname=" +thread.currentthread (). GetName () + "exited GetSize method"); returnSizevalue; }}
PackageSyn_out_asyn;/*** Created by Administrator on 2017/1/19 0019.*/ Public classThreadaextendsThread {PrivateMyList list; PublicThreada (MyList list) {Super(); This. List =list; } Public voidrun () { for(inti=0;i<10000;i++) {List.add ("Threada" + (i+1)); } }}
PackageSyn_out_asyn;/*** Created by Administrator on 2017/1/19 0019.*/ Public classThreadbextendsThread {PrivateMyList list; Publicthreadb (MyList list) {Super(); This. List =list; } Public voidrun () { for(inti=0;i<10000;i++) {List.add ("THREADB" + (i+1)); } }}
PackageSyn_out_asyn;/*** Created by Administrator on 2017/1/19 0019.*/ Public classRun { Public Static voidMain (string[] args) {MyList MyList=NewMyList (); Threada Threada=NewThreada (myList); Threada.setname (A); Threada.start (); THREADB threadb=Newthreadb (myList); Threadb.setname (B); Threadb.start (); }}
execution Result: threadname=A executes the Add method threadname=A exits the Add method threadname=A executes the Add method ThreadName =A exits the Add method threadname=A executes the Add method threadname=A exits the Add method threadname= b executes the Add method threadname=B Exits the Add method threadname=B Executes the Add method threadname=B Exits the Add method threadname =B Executes the Add method ThreadName=b exits the Add method
From the result, the code in the synchronization block is printed synchronously, and the current thread executes and exits in pairs. However, the execution of thread A and thread B is asynchronous, and it is possible that the dirty read environment occurs. Because the order of the methods executed by the thread is not deterministic, a logical error occurs when A and b two threads execute a method with a per cent judgment, and a dirty read is possible.
Use synchronized (non-this object) to synchronize blocks of code to troubleshoot dirty reads