synchronized 关键字 老生常谈
synchronized这个关键字要修饰一段代码。 一个线程(Thread)要运行一段代码,要获得的锁有两种 对象锁和类锁. 对象锁:thread要获得某个具体的对象的的锁,才能运行这段代码. 类锁: thread要获得这个类的锁,才能运行这段代码.
下面就按这两种锁来分类
1. 对象锁 a. synchronized 修饰普通方法
synchronized void syncMethod() {}
b. synchronized 修饰代码块
void method(Foo foo) {
synchronized(foo) {
}
}
synchronized void syncMethod() {}跟
void method() {
synchronized(this) {
}
}
效果是一样的。
2. 类锁 c. synchronized 修饰static方法
synchronized void static syncStaticMethod() {}
d. synchronized 修饰代码块
class Foo {
void method() {
synchronized(Foo.class) {
}
}
}
c和d的效果是一样的。
Tips: i. synchronized关键字放在void之前, public 之后
看到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();
}
}
- run方法里把synchronized注释掉,运行。 结果很乱.
- run方法把里用synchronized修饰,运行。 结果很整齐.
point 2不知道有什么用!!!