4 回答
TA贡献2036条经验 获得超8个赞
好多人说没有区别,这样吧,直接上代码和结果吧
public class Test {
static Runnable lock = new Runnable() {
@Override
public void run() {
synchronized (A.class) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
static Runnable syncA = new Runnable() {
@Override
public void run() {
A.syncShowTime();
}
};
static Runnable syncB = new Runnable() {
@Override
public void run() {
B.syncShowTime();
}
};
static Runnable lockA = new Runnable() {
@Override
public void run() {
A.lockShowTime();
}
};
static Runnable lockB = new Runnable() {
@Override
public void run() {
B.lockShowTime();
}
};
static Runnable instA = new Runnable() {
@Override
public void run() {
A a = new A();
a.instShowTime();
}
};
static Runnable instB = new Runnable() {
@Override
public void run() {
B b = new B();
b.instShowTime();
}
};
public static void main(String args[]) {
try {
new Thread(lock).start();
Thread.sleep(1000);
System.out.println("S:" + (int) (System.currentTimeMillis() / 1000L));
new Thread(syncA).start();
new Thread(syncB).start();
new Thread(lockA).start();
new Thread(lockB).start();
new Thread(instA).start();
new Thread(instB).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class A {
static synchronized void syncShowTime() {
System.out.println("A sync:" + (int) (System.currentTimeMillis() / 1000L));
}
static void lockShowTime() {
synchronized (A.class) {
System.out.println("A lock:" + (int) (System.currentTimeMillis() / 1000L));
}
}
void instShowTime() {
synchronized (A.class) {
System.out.println("A inst:" + (int) (System.currentTimeMillis() / 1000L));
}
}
}
class B {
static synchronized void syncShowTime() {
System.out.println("B sync:" + (int) (System.currentTimeMillis() / 1000L));
}
static void lockShowTime() {
synchronized (B.class) {
System.out.println("B lock:" + (int) (System.currentTimeMillis() / 1000L));
}
}
void instShowTime() {
synchronized (B.class) {
System.out.println("B inst:" + (int) (System.currentTimeMillis() / 1000L));
}
}
}
S:1469596337
B sync:1469596337
B lock:1469596337
B inst:1469596337
A inst:1469596341
A lock:1469596341
A sync:1469596341
TA贡献1829条经验 获得超7个赞
我想题主的意思是synchronized后面的括号里面放A.class和B.class有什么区别,两段代码并不是共存的,楼上的哥们好像理解错题主意思了。如果楼主是这个问题的话,那基本没啥区别。如果这两段代码分别在同一个类的不同方法中,那两个线程可以同时访问同一个对象的这两个方法,并没有什么影响,因为是不同的锁。so,看题主你的问题是什么了
TA贡献1995条经验 获得超2个赞
添加回答
举报