Synchronization with netizens discuss

zhaozj2021-02-17  162

The title is used in Java, and there will always be some seemingly instead of problems in the mind. So, I consider establishing a topic, specializing in discussing these issues, initially positioning it in the form of FAQ. This is the first one, which is initially discussed on synchronous problems. Why do you need synchronization? The following is an example of a simple counter: <% @ Page ContentType = "Text / HTML; Charset = GB2312"%> <% @ Page Import = "java.io. *"%> <%! Public int number; private String countFile; public int number () {try {ServletContext application = getServletContext (); countFile = application.getRealPath ( "/"); BufferedReader file = new BufferedReader (new FileReader (countFile "hits.txt")) Number = java.lang.integer.parseint (file.readline ()); Number ;} catCH (Exception E) {system.out.println (e);} return number;} public synchronized void counter () {Number ); Try {file f = new file (CountFile "Hits.txt"); PrintWriter PW = New PrintWriter (New FileWriter (f)); PW.Print (Number); PW.Close ();} catch (Exception E) {System.out.Println (e);}}%> <% IF (session.isnew ()) {crounter ();} Out.println (Number);%> Keyword Synchronized defines the concept of synchronization, which can be used as a method modifier and can be used as a method. It limits access to shared resources under multi-thread conditions. Method Counter () is latched to get and release the IO resource, that is, hold the LOCK of the object. This mechanism avoids a thread when performing file read and write operations, if it operates the resource, it will throw an exception. When do you need a synchronization mechanism? First, if the update of the object affects the read-only method, the read-only method should also be defined as synchronous, such as the above IO operation. Second, if two or more threads modify an object, then the method of performing the modification is defined as synchronous.

转载请注明原文地址:https://www.9cbs.com/read-31447.html

New Post(0)