In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "how to realize my robot girlfriend in singleton mode". In the operation of actual cases, many people will encounter this dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
The program code is as follows:
Public class GirlFriend {
Private String name
Public GirlFriend (String name) {
This.name = name
System.out.println ("Robot girlfriend made")
}
Public void smile () {
System.out.println ("smile: -)")
}
Public void housework () {
System.out.println ("to do housework")
}
Public void buKeMiaoShu () {
System.out.println (.)
}
}
The operation is also very simple, just create the object directly. Public static void main (String [] args) {
GirlFriend girlFriend = new GirlFriend ("Xiao Li")
GirlFriend.smile ()
GirlFriend.housework ()
GirlFriend.buKeMiaoShu ()
}
You see, we can get to work soon. The robot girlfriend is finished.
Smile: -)
To do the housework.
.
Xiao Shuai soon found a loophole, if there are enough materials, he can create countless objects. Soon, Xiao Shuai bought a set of materials on the black market, went home to start the machine, and sure enough created a second robot girlfriend. Xiao Shuai could not hide his excitement and thought that if he went to the black market to buy a few sets of materials, he would be able to print a lot of "girlfriends".
Singleton mode
The monitoring system of Innovation Genetics soon discovered the problem, and engineers worked overtime to upgrade the system online. They adopted a design pattern called singleton pattern to ensure that only one object could be generated by a machine.
The updated code is as follows: public class GirlFriend {
Private static GirlFriend girlFriend
Private String name
Private GirlFriend (String name) {
This.name = name
System.out.println ("Robot girlfriend made")
}
/ * *
* object is obtained by getInstance method
* @ param name
* @ return
, /
Public static GirlFriend getInstance (String name) {
If (girlFriend = = null) {
GirlFriend = new GirlFriend (name)
}
Return girlFriend
}
Public void smile () {
System.out.println ("smile: -)")
}
Public void housework () {
System.out.println ("to do housework")
}
Public void buKeMiaoShu () {
System.out.println (.)
}
}
Public static void main (String [] args) {
GirlFriend girlFriend = GirlFriend.getInstance ("Xiao Li")
GirlFriend.smile ()
GirlFriend.housework ()
GirlFriend.buKeMiaoShu ()
}
The engineers of Innovation Genetics were so satisfied that they opened a grand party to celebrate the successful completion of the work. Xiao Shuai spent a lot of money, bought several sets of materials on the black market, and planned to go home to create a "harem group". It was really nice to think about the days to come. Xiao Shuai opened the program foolishly and ran it many times. All he got was the same object. Did the dream of "harem" break? Handsome is not reconciled to it. After several days of meditation, Xiao Shuai finally came up with a way to crack it, which is multithreaded: public static void main (String [] args) {
For (int I = 0; I < 5; iTunes +) {
New Thread (new Runnable () {
@ Override
Public void run () {
GirlFriend girlFriend = GirlFriend.getInstance ("Xiao Li")
System.out.println (girlFriend)
}
}) .start ()
}
}
Five threads run at the same time, and three different objects are successfully created. The robot girlfriend is finished.
Singleton.singleton.GirlFriend@95458f7
The robot girlfriend is finished.
The robot girlfriend is finished.
Singleton.singleton.GirlFriend@d9d8ad0
Singleton.singleton.GirlFriend@383a0ba
Singleton.singleton.GirlFriend@d9d8ad0
Singleton.singleton.GirlFriend@d9d8ad0
"Whoa. Whoo. Whoo." The alarm of Innovation Genetics went off again, and the engineers looked confused. How could there be a flaw in such a perfect singleton model? Finally, it was the technical director himself who explained to the engineers and drew a picture by the way:
If both threads 1 and 2 judge the girlFriend as empty, they will each create an object and eventually return two different objects.
The engineers suddenly realized. "does anyone know how to improve it?" Asked the technical director. Lazy style "this is simple, add a synchronized keyword to the getInstance method!" Programmer Lao Wang said proudly. / * *
* object is obtained by getInstance method
* @ param name
* @ return
, /
Public synchronized static GirlFriend getInstance (String name) {
If (girlFriend = = null) {
GirlFriend = new GirlFriend (name)
}
Return girlFriend
}
"this is true, but," said the technical director, "have you ever thought about efficiency?"the synchronized synchronization method can only be used when the object is created for the first time, that is, once the girlFriend object is created, the synchronization feature is not needed, but the synchronization code will be entered every time the getInstance method is called, which seriously reduces the efficiency." The technical director pointed out the problem sharply. There is another way to use global variables to create objects when the class is loaded, so the instance creation process is thread-safe. " Programmer Xiao Li also came up with an idea. Public class GirlFriend {
/ / it is thread-safe to create an object when the class is loaded
Private static GirlFriend girlFriend = new GirlFriend ("Xiao Li")
Private String name
Private GirlFriend (String name) {
This.name = name
System.out.println ("Robot girlfriend made")
}
/ * *
* object is obtained by getInstance method
* @ return
, /
Public static GirlFriend getInstance () {
Return girlFriend
}
Public void smile () {
System.out.println ("smile: -)")
}
Public void housework () {
System.out.println ("to do housework")
}
Public void buKeMiaoShu () {
System.out.println (.)
}
}
"this is an approach, but there are several issues to consider in this implementation," said the technical director. "
Delayed loading is not supported (create an instance when the object is actually used), the object is created when the class is loaded, and if the object is not used once in the whole program, it is wasted to create it in advance.
Can not control the number of objects, we can declare multiple objects, such as: GirlFriend girlFriend1;GirlFriend girlFriend2;GirlFriend girlFriend3.
We may not have enough information to instantiate each object during static initialization, and the constructor parameters of the object may depend on the results of the later operations of the program.
However, we have to learn how to use it. If it takes time to create an object, it will be slow to create it when we use it. We want to create it in advance when the program is loaded. We can use this way.
"is there any other way?" Pursued the technical director. Double check "there is another way to put the synchronization lock into the method, double check." Lao Wang, a programmer, thought about it for a long time and finally came up with another way. Public class GirlFriend {
The / / volatile keyword ensures that the girlFriend objects seen by each thread are up to date
Private volatile static GirlFriend girlFriend
Private String name
Private GirlFriend (String name) {
This.name = name
System.out.println ("Robot girlfriend made")
}
/ * *
* object is obtained by getInstance method
* @ param name
* @ return
, /
Public static GirlFriend getInstance (String name) {
If (girlFriend = = null) {
Synchronized (GirlFriend.class) {
If (girlFriend = = null) {
GirlFriend = new GirlFriend (name)
}
}
}
Return girlFriend
}
Public void smile () {
System.out.println ("smile: -)")
}
Public void housework () {
System.out.println ("to do housework")
}
Public void buKeMiaoShu () {
System.out.println (.)
}
}
"when checking the girlFriend object, if you enter the synchronization code for null, each thread redetermines whether the girlFriend object is empty, and the volatile keyword ensures that the girlFriend object seen by each thread is up-to-date (in higher versions of Java, volatile is no longer needed)." if the girlFriend object has been created, it will not enter the synchronization code in the future, which ensures efficiency. " Lao Wang explained. "well, this is a good way to solve the low performance of the lazy method and the delayed loading problem of the hungry method. Let's use this scheme to upgrade the code." The technical director praised. Summary singleton pattern (Singleton Pattern): the singleton pattern ensures that there is only one instance of a class and provides a global access point to it. The singleton model has three main points:
There can be only one instance of a class
It must create this instance on its own
It must provide this example to the entire system on its own.
Singleton mode is an object creation mode. Singleton mode is also list mode or singleton mode. The implementation of a single case has the following classical implementation methods:-the advantage of the lazy type over the hungry type is to support delayed loading. However, this implementation will lead to frequent locking, releasing locks, and low concurrency, and frequent calls will lead to performance bottlenecks. In the implementation of hungry Chinese style, static instances are initialized during class loading, so the creation of instances is thread-safe. However, this implementation does not support delayed loading of instances. -the implementation of dual detection is a singleton implementation that supports both delayed loading and high concurrency. As long as the instance is created, calling the getInstance () function will not enter the locking logic.
This is the content of "how to realize my robot girlfriend in singleton mode". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.