[JavaSE] concurrent programming (Inter-thread communication), javase thread
Create a Resource
Define the member variable String name
Define the member variable int age
Creates an Input class and implements the Runnable interface.
Define a constructor Input (). Input parameter: Resource object
Run () method
Define while (true) to assign values to the attributes of the Resuorce object
Create an Output class and implement the Runnable interface
Define a constructor Output () and input the parameter: Resource object
Run () method
Define while (true) to print the attributes of the Resuorce object
In the main method
Get Resource object, new
Obtain the Input object, which is new. The construction parameter is the Resource object.
Get the Output object, new, and construct the parameter: Resource object
Get the Thread object, new, and construct the parameter: Runnable object
Call the start () method of the Thread object to enable the Thread.
At this time, there will be thread security issues. You can see that Chinese characters and Pinyin are mixed.
Tao shihan ==== male
Taoshihan ==== nan
Tao shihan ==== nan
Tao shihan ==== nan
Tao shihan ==== male
Tao shihan ==== male
Tao shihan ==== nan
Tao shihan ==== nan
Taoshihan ==== nan
Taoshihan ==== nan
Use synchronized () {} to synchronize code block packages to operate on the same resource
Note that the number of synchronization threads should be added to all threads.
Check whether the lock is the same. The lock parameter in synchronized () is a unique resource.
Use synchronized () {} to wrap the assignment and print above. Lock: Resource object (unique)
Check the result. There is no security problem at this time.
Tao shihan ==== male
Tao shihan ==== male
Tao shihan ==== male
Taoshihan ==== nan
Taoshihan ==== nan
Taoshihan ==== nan
Deadlock: Nested synchronization in synchronization and inconsistent locks can cause deadlocks.
/*** Resource ** @ author taoshihan **/class Resource {String name; String sex ;} /*** Input ** @ author taoshihan **/class Input implements Runnable {private Resource resource; public Input (Resource resource Resource) {this. resource = resource ;}@ Override public void run () {// switch boolean flag = true; while (true) {synchronized (resource) {if (flag) {resource. name = "taoshihan"; resource. sex = "nan";} els E {resource. name = "Tao shihan"; resource. sex = "male" ;}flag =! Flag ;}}}/*** Output ** @ author taoshihan **/class Output implements Runnable {private Resource resource; public Output (Resource resource) {this. resource = resource;} @ Override public void run () {while (true) {synchronized (resource) {System. out. println (resource. name + "=" + resource. sex) ;}}} public class InputOutputDemo {/*** @ param args */public static void main (String [] args) {Resource resource = new Resource (); input input = new Input (resource); Output output = new Output (resource); Thread t1 = new Thread (input); Thread t2 = new Thread (output); t1.start (); t2.start ();}}