java同步鎖的使用3
在一個對象中的多個方法上都加上synchronized,代表同時執行這些方法時,是同步的,同步鎖是屬于對象的不是單個方法的。package test;
public class Test6 {
public synchronized void get1(String s){
System.out.println(s);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void get2(String s){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(s);
}
public static void main(String[] args) {
final Test6 t =new Test6();
new Thread(new Runnable() {
@Override
public void run() {
t.get1("a");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.get2("b");
}
}).start();
}
}