多个线程使用一把锁,多个线程访问同一个对象的方法或者属性。
package test;
public class Test4 {
public synchronized void get(String s){
if("c".equals(s)){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s);
}
public static void main(String[] args) {
final Test4 t =new Test4();
new Thread(new Runnable() {
@Override
public void run() {
t.get("a");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.get("b");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.get("c");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
t.get("d");
}
}).start();
}
}