Synchronized 有3种形式:
1.锁静态方法:不同线程调用两个方法都是互斥的,而且当method1被某个线程占用,其他线程无法使用method2:
public synchronized static void method1(){}
public synchronized static void method2(){}
2.锁类:不同线程调用不同对象的method3方法是互斥的,并且与SynchrionizedDemo的中加的Synchronized静态方法互斥,但是不与SynchrionizedDemo的Synchronized非静态方法互斥:
public void method3(){
synchronized (SynchronizedDemo.class){}
}
3.锁对象,不同的线程调用同一对象的synchronized方法是互斥的。
public void method3(){
synchronized (this){}
}
public static void method5(){}
public static void method6(){}
下边举例说明:
1.锁类的情况下,不同的线程thread3,thread4分别调用不同对象demo1,demo2的相同的方法method3,会顺序执行
public class SynchronizedDemo {
public void method3(){
synchronized (SynchronizedDemo.class){
for (int i = 0; i<=5;i++){
System.out.println(Thread.currentThread().getName() +"method3:"+i);
}
}
}
public static void main(String[] args) {
final SynchronizedDemo demo1 = new SynchronizedDemo();
final SynchronizedDemo demo2 = new SynchronizedDemo();
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
demo2.method3();
}
},"thread3");
Thread thread4 = new Thread(new Runnable() {
@Override
public void run() {
demo1.method3();
}
},"thread4");
thread3.start();
thread4.start();
}
}
执行结果如下:
thread3method3:0
thread3method3:1
thread3method3:2
thread3method3:3
thread3method3:4
thread3method3:5
thread4method3:0
thread4method3:1
thread4method3:2
thread4method3:3
thread4method3:4
thread4method3:5
2.对象锁:不同的线程thread1,thread2同是调用对象demo1的不同方法method1,method2
public class SynchronizedDemo {
public synchronized void method1(){
for (int i = 0; i<=5;i++){
System.out.println(Thread.currentThread().getName() +"method1:" + i);
}
}
public synchronized void method2(){
for (int i = 0; i<=5;i++){
System.out.println(Thread.currentThread().getName() +"method2:"+i);
}
}
public static void main(String[] args) {
final SynchronizedDemo demo1 = new SynchronizedDemo();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
demo1.method1();
}
},"thread1");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
demo1.method2();
}
},"thread2");
thread1.start();
thread2.start();
}
}
执行结果如下:
thread1method1:0
thread1method1:1
thread1method1:2
thread1method1:3
thread1method1:4
thread1method1:5
thread2method2:0
thread2method2:1
thread2method2:2
thread2method2:3
thread2method2:4
thread2method2:5