- 同步方法只影响其他线程调用同一同步方法,不影响调用其他非同步方法,或其他锁资源的同步方法.
测试代码
public class Test02 {
Object o = new Object();
public synchronized void m1() {
System.out.println("public synchronized void m1 start");
try {
Thread.sleep(3000); //睡个三秒
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("public synchronized void m1 end");
}
public void m3() {
synchronized (o) {
System.out.println("public m3 start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("public m3 end");
}
}
public void m2() {
System.out.println("public m2 start");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("public m2 end");
}
public static class MyThread implements Runnable {
int i = 0;
Test02 t;
public MyThread(int i, Test02 t) {
this.i = i;
this.t = t;
}
@Override
public void run() {
if(i == 0) {
this.t.m1();
}
if(i == 1) {
this.t.m2();
}
if(i == 2) {
this.t.m3();
}
}
}
public static void main(String[] args) {
Test02 t = new Test02();
new Thread(new Test02.MyThread(0, t)).start();
new Thread(new Test02.MyThread(1, t)).start();
new Thread(new Test02.MyThread(2, t)).start();
}
}
运行结果
public synchronized void m1 start
public m2 start
public m3 start
public m2 end
public m3 end
public synchronized void m1 end
QA
- 尽量自己定义一个Object对象.如果使用this的话比较重量级,效率低.