N
nytimescnn
I've read some discuession about lock() for thread-safe. I am wondering
what will be the differce between below two code segment?
Code 1:
class A
{
private static Object padlock = new Object();
...// some codes
public static Method()
{
lock(padlock)
{
...// some codes
}
}
}
Code 2:
class A
{
...// some codes
public static Method()
{
private Object padlock = new Object(); //HERE it is NOT static
variable
lock(padlock)
{
...// some codes
}
}
}
My understanding is only Code1 works fine, since it will lock on a
common static variable for all threads. Code2 will NOT work since each
time it will create a private instance, and lock will be on different
(new created) instance each time. Am I correct?
Thanks,
what will be the differce between below two code segment?
Code 1:
class A
{
private static Object padlock = new Object();
...// some codes
public static Method()
{
lock(padlock)
{
...// some codes
}
}
}
Code 2:
class A
{
...// some codes
public static Method()
{
private Object padlock = new Object(); //HERE it is NOT static
variable
lock(padlock)
{
...// some codes
}
}
}
My understanding is only Code1 works fine, since it will lock on a
common static variable for all threads. Code2 will NOT work since each
time it will create a private instance, and lock will be on different
(new created) instance each time. Am I correct?
Thanks,