One.
The code in the previous section does not write very glasses, such as the properties in, should all be private. We should not directly access the attributes in the resource because it has no security.
What about blind assignment? In order to be controllable, it means that the attributes within the resource need to be privatized and provide access to the method externally. So the code in the previous section needs to be rewritten.
The resource description class is modified first, as to why the set method has two parameters written because name and sex are assigned at the same time, so they are defined directly together.
And the class provides a way to directly output name and sex, and later in the program does not need to write such a long output statement. This output problem is relatively simple
Where are the key questions? If this is the case, the code below will be changed. Why? cannot be called directly, such as r.name .... This can only be written as R.set ().
So where is the real multithreading security problem? Just now because R called name and sex, and then when the assignment, R.name=mike, Sex=nan has not been assigned to the end, is directly taken away from the cause. And now, where is the name and sex assignment? In the Set () method,
If this is assigned a name, there will be an accident without a sex assignment. So the two sentences need to be synchronized.
We just need to make sure that the following three sentences are synchronized, (why?) In this case, we can think of any object we use. Using a custom object is also OK, using the existing this in this class. The This direct write synchronization function in a thread is simpler.
We know that the method of wait and notify must belong to this synchronization, because it is the method of locking. Used to manipulate the method on the specified thread lock. Therefore, we write if (flag), and here in the handling of exceptions, we can not label R, can only be this. Notify front Add this, (lock), all the same, can be omitted.
After saying the above program changes, the following is simple.
That should be the case in development, where my attributes are encapsulated, and the methods of accessing properties are provided externally.
If you need to synchronize, add a sync to the finish, so there is no error.
DOS results show no problem,
So far, the small sample is basically done, and how to check the application of security problems, the use of synchronization and synchronous use of the premise, the use of wake-up mechanism.
java-Preliminary Understanding-14th-inter-thread communication-wait-wake mechanism-code optimization