多个线程访问同多个对象,同步方法加static,表示此方法属于类,所有此对象的此方法执行需要同步
package test;
public class Test5 {
public static synchronized void get(String s){
if("a".equals(s)){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s);
}
public static void main(String[] args) {
final Test5 t =new Test5();
final Test5 t1 =new Test5();
new Thread(new Runnable() {
@Override
public void run() {
t.get("a");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t1.get("b");
}
}).start();
}
}