synchronized 关键字 老生常谈

[list]
[*]synchronized这个关键字要修饰一段代码。
[*]一个线程(Thread)要运行一段代码,要获得的锁有两种 对象锁和类锁.
对象锁:thread要获得某个具体的对象的的锁,才能运行这段代码.
类锁: thread要获得这个类的锁,才能运行这段代码.
[/list]


下面就按这两种锁来分类

[b]1. 对象锁[/b]
a. synchronized 修饰普通方法
synchronized void syncMethod() {}

b. synchronized 修饰代码块
    void method(Foo foo) {
synchronized(foo) {
}
}

[注]
synchronized void syncMethod() {}跟
void method() {
synchronized(this) {
}
}
效果是一样的。

[b]2. 类锁[/b]
c. synchronized 修饰static方法
synchronized void static syncStaticMethod() {}

d. synchronized 修饰代码块
class Foo {
void method() {
synchronized(Foo.class) {
}
}
}

[注]c和d的效果是一样的。

Tips:
i. synchronized关键字放在void之前, public 之后

[b][color=red][补充1][/color][/b]
看到synchronized修饰runnable 的run方法。

package com.test.testrun;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class SyncRun implements Runnable {

public void run() {
// synchronized(this) { //point 1
for (int i = 0; i < 100; i++) {
System.out.println(i);
Thread.yield();
}
// }
}

}

public class TestRunMethod {

public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
SyncRun r = new SyncRun();
for (int i = 0; i < 10; i++) {
// exec.execute(new SyncRun()); //point 2
new Thread(r).start();
}

try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {

e.printStackTrace();
}
exec.shutdownNow();
}
}


1. run方法里把synchronized注释掉,运行。
结果很乱.
2. run方法把里用synchronized修饰,运行。
结果很整齐.

point 2不知道有什么用!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值