java synchronized int_java synchronized锁不同class的区别是什么

好多人说没有区别,这样吧,直接上代码和结果吧

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值