1 //Communication between Threads: The task of the thread is different, but the data for the thread operation is the same. 2 3 //describe the data4 classResource5 {6 PublicString name;7 PublicString gender;8 PublicResource () {}9 }Ten One //describe input tasks A classInputImplementsRunnable - { - PrivateResource Res; the PublicInput (Resource res) - { - This. res =Res; - } + Public voidRun () - { + inti = 1; A while(true) at { - synchronized(RES)//Plus sync lock ① - { - if(i==1) - { -Res.name = "Pig xiaoming"; inRes.gender = "Male"; - } to Else + { -Res.name = "Leg Leg"; theRes.gender = "female"; * } $i= (++i)%2;Panax Notoginseng } - } the } + } A the //describe the output task + classOutputImplementsRunnable - { $ PrivateResource Res; $ PublicOutput (Resource res) - { - This. res =Res; the } - Public voidRun ()Wuyi { the while(true) - { Wu synchronized(RES)//Plus sync lock ②,① Place and here for the same lock! - { AboutSystem.out.println (Res.name + "..." +res.gender); $ } - } - } - } A + classTest the { - Public Static voidMain (string[] args) $ { the //Create a resource theResource res =NewResource (); the //Create an input task theInput input =NewInput (res); - //Create an output task inOutput output =NewOutput (res); the //Creating an input thread theThread T1 =NewThread (input); About //creating an Output thread theThread t2 =NewThread (output); the //Start Thread the T1.start (); + T2.start (); - the }Bayi}
Two basic requirements for synchronization:
- There are at least two threads
- Use the same lock
If you do not use synchronization, the following error will occur:
After using synchronization, the error no longer occurs:
Communication between threads sharing data security issues