There is a public calculate() method a singleton class. If there are 2 threads to call the calculate() at the same time. I wonder if one thread must wait until another thread executing calculate() is finished?
If it is not a singleton class. I changed the mthod to static public calculate(). I still wonder if one thread must wait until another thread executing calculate() is finished?
Whether or not you have a singleton, nothing automatically waits without some synchronization code. And don't change a method that should not static to be static! [ January 03, 2006: Message edited by: Jeff Albrechtsen ]
if you don't put volatile key word for the variable, thread will have a their own local copy even though variable is static when threads are not synchronized. [ January 03, 2006: Message edited by: Jignesh Patel ]
Joined: Dec 22, 2002
Thank you, guys,
I am still confused about static method. I know a static varialbe has only one in memory. I think static method also has only one in memory, can not make a copy for the threads. So 2 threads can only call it one by one until one calling is done.
I think static method also has only one in memory, can not make a copy for the threads.
In general, there is only ever a single copy of the code for any method, static or not (barring complications like multiple class loaders, which we'll ignore for the moment.) But this does not stop multiple threads from using that code at the same time, any more than you and a friend have any problem both looking out a single window at the same time.
Only the "synchronized" keyword can mark a method so that only one thread can use it at a time.
Extending on what Ernest said, every method call gets its own stack space for local variables and the like - whether they are in the same thread (recursion) or not.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus