静态同步synchronized方法与synchronized(class)代码块
1. 静态同步synchronized方法
- synchronized关键字加到static静态方法上是给Class类上锁
- synchronized关键字加到非静态方法上是给对象上锁
1.1 Service
public class Service {
//static
synchronized public static void printA() {
try {
System.out.println(Thread.currentThread().getName() + " in printA");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " out printA");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//static
synchronized public static void printB() {
System.out.println(Thread.currentThread().getName() + " in printB");
System.out.println(Thread.currentThread().getName() + " out printB");
}
//非static
synchronized public void printC() {
System.out.println(Thread.currentThread().getName() + " in printC");
System.out.println(Thread.currentThread().getName() + " out printC");
}
}
1.2 ThreadA
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service){
super();
this.service = service;
}
@Override
public void run(){
service.printA();
}
}
1.3 ThreadB
public class ThreadB extends Thread{
private Service service;
public ThreadB(Service service){
super();
this.service = service;
}
@Override
public void run(){
service.printB();
}
}
1.4 ThreadC
public class ThreadC extends Thread {
private Service service;
public ThreadC(Service service){
super();
this.service = service;
}
@Override
public void run(){
service.printC();
}
}
1.5 Test
public class Test {
public static void main(String[] args) {
Service service = new Service();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
ThreadC c = new ThreadC(service);
c.setName("C");
c.start();
}
}
1.6 运行结果
A in printA
C in printC
C out printC
A out printA
B in printB
B out printB
从结果上看A和B是共用一个锁,A和C不是共用同一个锁
2. synchronized(class)代码块
synchronized(class)的作用和synchronized static 方法一样,都是作用于这个类的所有对象。
2.1 修改Service
public class Service {
public static void printA() {
synchronized (Service.class) {
try {
System.out.println(Thread.currentThread().getName() + " in printA");
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " out printA");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void printB() {
synchronized (Service.class) {
System.out.println(Thread.currentThread().getName() + " in printB");
System.out.println(Thread.currentThread().getName() + " out printB");
}
}
}
2.2 修改Test
public class Test {
public static void main(String[] args) {
Service service = new Service();
ThreadA a = new ThreadA(service);
a.setName("A");
a.start();
ThreadB b = new ThreadB(service);
b.setName("B");
b.start();
}
}
2.3 运行结果
A in printA
A out printA
B in printB
B out printB