Synchronization with netizens discuss

xiaoxiao2021-03-06  52

Inscription

It is also a bit time to use Java, and there will always be some seemingly instead of problems in 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 ()) {

Counter ();

}

Out.println (Number);

%>

Keywords synchronized defines the concept of synchronization, which can be modified as a method or as a method within the 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-115012.html

New Post(0)