------Java EE Training, Android training, iOS training, and looking forward to communicating with you! -------
Example:
//encapsulate a resource as an objectclassresour{String name; String gender;}//to encapsulate a task performed by a thread as an objectclassInputImplementsrunnable{PrivateResour R; Input (Resour r) { This. R =R; } Public voidrun () {intX =0; while(true) { if(x==0) {R.name= "Travis"; R.gender= "Male"; } Else{r.name= "Zhang Miao"; R.gender= "female"; } x= (x+1)%2; } }}classOutputImplementsrunnable{PrivateResour R; Output (Resour r) { This. R =R; } Public voidrun () { while(true) {System.out.println (R.name+" "+R.gender); } }}classmylock{StaticObject Locka =NewObject (); StaticObject lockb =NewObject ();} classMlpcdemo { Public Static voidMain (string[] args) {resour R=NewResour (); Input in=NewInput (R); Output out=NewOutput (R); Thread Th0=NewThread (in); Thread Th1=NewThread (out); Th0.start (); Th1.start (); }}
So, we add synchronization to the assigned code block. It is important to be aware of what code is to be synchronized.
//encapsulate a resource as an objectclassresour{String name; String gender;}//to encapsulate a task performed by a thread as an objectclassInputImplementsrunnable{PrivateResour R; Object obj=NewObject (); Input (Resour r) { This. R =R; } Public voidrun () {intX =0; synchronized (obj){
while(true) { if(x==0) {R.name= "Travis"; R.gender= "Male"; } Else{r.name= "Zhang Miao"; R.gender= "female"; } x= (x+1)%2; } } }}classOutputImplementsrunnable{PrivateResour R; Output (Resour r) { This. R =R; } Public voidrun () { while(true) {System.out.println (R.name+" "+R.gender); } }}classmylock{StaticObject Locka =NewObject (); StaticObject lockb =NewObject ();} classMlpcdemo { Public Static voidMain (string[] args) {resour R=NewResour (); Input in=NewInput (R); Output out=NewOutput (R); Thread Th0=NewThread (in); Thread Th1=NewThread (out); Th0.start (); Th1.start (); }}
On the surface, the assignment code block was added to the synchronization, but the results of the operation still appeared in the case of names and gender confusion.
Therefore, the reason for the analysis, the definition of synchronization has two prerequisites, the first input and output of the two threads do not use the same lock.
Second, carefully observe the following code:
Newnew Thread (out);
Th0.start ();
Th1.start ();
Only one thread is executing, either input or output!
However, it is easy to solve the problem. Add the same lock to the synchronization functions of the different threads.
Errors to be aware of:
1 Public voidRun ()2 {3 intX =0;4 synchronized(R)//This will cause the thread to walk forever within the code block of this synchronization function 5 {6 while(true)7 {8 if(x==0)9 {TenR.name = "Travis"; OneR.gender = "Male"; A } - Else - { theR.name = "Zhang Miao"; -R.gender = "female"; - } -x = (x+1)%2; + } - } +}
Dark Horse Programmer-Learning Diary (communication between multiple threads)