Lock需要自己释放锁,synchronized执行完自动释放锁
package baseMethod;
public class SynAndStaticSyn {
/**
* synchronized对当前实例上锁,[ˈsɪŋkrənaɪzd]同步
*/
public synchronized void isSynA() {
for (int i = 0; i < 5; i++) {
System.out.println("isSynA:" + i);
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
public synchronized void isSynB() {
for (int i = 0; i < 5; i++) {
System.out.println("isSynB:" + i);
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
/**同步代码块,代码块执行速度比方法块,一样是实例锁*/
public void isSynC(){
synchronized (this){
for (int i = 0; i < 5; i++) {
System.out.println("isSynC:" + i);
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
}
/**
* synchronize对类上锁,对所有实例有效
*/
public static synchronized void cSynA() {
for (int i = 0; i <5 ; i++) {
System.out.println("cSynA");
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
public static synchronized void cSynB() {
for (int i = 0; i <5 ; i++) {
System.out.println("cSynC");
try {
Thread.sleep(500);
} catch (InterruptedException ignored) {
}
}
}
public static void main(String[] args) {
SynAndStaticSyn A = new SynAndStaticSyn();
SynAndStaticSyn B = new SynAndStaticSyn();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
A.isSynC();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
A.isSynA();
}
});
/* brief summary
--实例锁synchronize--
1.A.isSynA()& A.isSynB();
同一个实例的不同方法,线程执行完再执行下一个,同样的锁
2.A.isSynA()& B.isSynA();
不同实例的相同方法或不同方法,线程锁交替进行,不同样的锁
--static synchronize 类锁--
1.cSynA&cSynB
同个类的不同static方法,线程执行完再执行下一个,同样的锁
2.A.isSynA()& cSynA()或CSynB();
实例和类的对比,线程交替进行,不同样的锁
*/
threadA.start();
threadB.start();
}
}