一、使用零长度的byte[]对象作为锁
class Foo implements Runnable
{
private byte[] lock = new byte[0]; // 特殊的instance变量
Public void methodA()
{
synchronized(lock) { //… }
}
//…..
}
注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock
= new Object()则需要7行操作码。
二、synchronized作用范围
1、只对对象生效,不对类生效
public synchronized void test1(){
while (i<=5){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":print-"+i);
i++;
}
public void test(){
synchronized (this){
while (i<=5){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":print-"+i);
i++;
}
}
}
private final int[] lock = new int[0]; public void test2(){ { synchronized (lock){ while (i<=5){ try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":print-"+i); i++; } } } }b、
2、对类生效
静态变量
private static final int[] lock4 = new int[0]; public void test4(){ { int j = 0; synchronized (lock4){ while (j<=5){ try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":print-"+j); j++; } } } }
类名作为锁
public void test5(){
{
int j = 0;
synchronized (SynchronizedClass2.class){
while (j<=5){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":print-"+j);
j++;
}
}
}
}
3、同一对象中多个对象锁不会互相影响
private final int[] lock2 = new int[0]; public void test2(){ { int j = 0; synchronized (lock2){ while (j<=5){ try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":print-"+j); j++; } } } } private final int[] lock3 = new int[0]; public void test3(){ { synchronized (lock3){ while (i<=5){ try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+":print-"+i); i++; } } } }
4、静态方法加锁不会影响同一类、同一对象的其他方法,只影响同一类的自身方法;非静态方法加锁影响同一对象中的所有加锁方法,不影响同一类其他对象的加锁方法。
来源:oschina
链接:https://my.oschina.net/u/2958224/blog/782467