当前位置: 技术问答>java相关
请教synchronized问题!!
来源: 互联网 发布时间:2015-04-10
本文导语: 在jb的帮助的文档,我有一点不明白 A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method(静态的方法??为什么是静态方法?), the lock associated with the Class object(类对象?) (§20...
在jb的帮助的文档,我有一点不明白
A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method(静态的方法??为什么是静态方法?), the lock associated with the Class object(类对象?) (§20.3) for the method's class is used(). For an instance method, the lock associated with this (the object for which the method was invoked) is used. These are the same locks that can be used by the synchronized statement; thus, the code:
class Test {
int count;
synchronized void bump() { count++; }//为什么同步呀??
static int classCount;
static synchronized void classBump() {//为用同步
classCount++;
}
}
has exactly the same effect as:
class BumpTest {
int count;
void bump() {
synchronized (this) {
count++;
}
}
static int classCount;
static void classBump() {
try {
synchronized (Class.forName("BumpTest")) {
classCount++;
}
} catch (ClassNotFoundException e) {
...
}
}
}
A synchronized method acquires a lock (§17.1) before it executes. For a class (static) method(静态的方法??为什么是静态方法?), the lock associated with the Class object(类对象?) (§20.3) for the method's class is used(). For an instance method, the lock associated with this (the object for which the method was invoked) is used. These are the same locks that can be used by the synchronized statement; thus, the code:
class Test {
int count;
synchronized void bump() { count++; }//为什么同步呀??
static int classCount;
static synchronized void classBump() {//为用同步
classCount++;
}
}
has exactly the same effect as:
class BumpTest {
int count;
void bump() {
synchronized (this) {
count++;
}
}
static int classCount;
static void classBump() {
try {
synchronized (Class.forName("BumpTest")) {
classCount++;
}
} catch (ClassNotFoundException e) {
...
}
}
}
|
同步就仿佛大号时,自然希望一个人一个坑,免得相互干扰。
|
用在多线程中。比如:MyThread类继承于Thread,我们要用for(;;)循环来创建MyThread类100次。在MyThread类有个线程计数器(int),创建MyThread时加1,退出时减1,这个计数器不可能同时又加又减,synchronized就是用来实现这个功能的。
如上例,当运行到 synchronized (Class.forName("BumpTest")) {
classCount++;
}时其它线程不能对classCount进行操作,只有程序运行完synchronized...{...}后其它线程才能操作classCount,同时只能有一个线程操作classCount。
如上例,当运行到 synchronized (Class.forName("BumpTest")) {
classCount++;
}时其它线程不能对classCount进行操作,只有程序运行完synchronized...{...}后其它线程才能操作classCount,同时只能有一个线程操作classCount。
|
csdn_cloud(拔光毛的兔兔) 说得很经典
|
For a class(static) method, we don't need to create instance for the class, so the lock associated with the Class objectfor the method's class is used. It work like "synchronized(Class.forName("BumpTest"))".
|
jb中的例子大多是没有背景的。
在分布式客服多用户时,假如多人同时访问服务器上的同一个文件,当然就应该用同步。
在分布式客服多用户时,假如多人同时访问服务器上的同一个文件,当然就应该用同步。