public class MyThread {
private static int i=5;
public static synchronized void print(String a) {
if(a.equals("a")) {
i--;
System.out.println("a "+i);
}else {
i=i-2;
System.out.println("b "+i);
}
System.out.println("last "+i);
}
public static void main(String[] args) {
final MyThread thread=new MyThread();
final MyThread thread1=new MyThread();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
thread.print("a");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
thread1.print("b");
}
}).start();
}
}
a 4
last 4
b 2
last 2
在变量和方法上加static ,在该类的所有对象是具有相同的引用的
public class MyThread {
private int i=5;
public synchronized void print(String a) {
if(a.equals("a")) {
i--;
System.out.println("a "+i);
}else {
i=i-2;
System.out.println("b "+i);
}
System.out.println("last "+i);
}
public static void main(String[] args) {
final MyThread thread=new MyThread();
final MyThread thread1=new MyThread();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
thread.print("a");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
thread1.print("b");
}
}).start();
}
}
a 4
last 4
b 3
last 3
由此可见,synchronized 一个对象一把锁,多个线程多个锁
Synchronized 其他特点
1.Synchronized 锁重入:作用避免死锁
2.出现异常时,锁自动释放