代码如下
package chapterTwo.synchronize;
import chapterTwo.synchronizeUtils.Service;
import chapterTwo.synchronizeUtils.*;
public class Run {
public static void main(String[] args){
Service service = new Service();
ThreadA threadA = new ThreadA(service);
threadA.setName("A");
threadA.start();
ThreadB ThreadB = new ThreadB(service);
ThreadB.setName("B");
ThreadB.start();
ThreadC ThreadC = new ThreadC(service);
ThreadC.setName("C");
ThreadC.start();
}
}
----------
package chapterTwo.synchronizeUtils;
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service) {
super();
this.service = service;
}
@Override
public void run(){
super.run();
service.printA();
}
}
-----------
package chapterTwo.synchronizeUtils;
public class ThreadB extends Thread {
private Service service;
public ThreadB(Service service) {
super();
this.service = service;
}
@Override
public void run(){
super.run();
service.printB();
}
}
----------
package chapterTwo.synchronizeUtils;
public class ThreadC extends Thread {
private Service service;
public ThreadC(Service service) {
super();
this.service = service;
}
@Override
public void run(){
super.run();
service.printC();
}
}
------------
package chapterTwo.synchronizeUtils;
public class Service {
synchronized public static void printA(){
try {
System.out.println("线程:" + Thread.currentThread().getName() + ",进入printA方法。");
Thread.sleep(3000);
System.out.println("线程:" + Thread.currentThread().getName() + ",离开printA方法。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public static void printB(){
try {
System.out.println("线程:" + Thread.currentThread().getName() + ",进入printB方法。");
Thread.sleep(3000);
System.out.println("线程:" + Thread.currentThread().getName() + ",离开printB方法。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public void printC(){
try {
System.out.println("线程:" + Thread.currentThread().getName() + ",进入printC方法。");
Thread.sleep(3000);
System.out.println("线程:" + Thread.currentThread().getName() + ",离开printC方法。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
结果:
总结:
- 同一个类的类锁方法及代码块是同步的。
- 同一个类的对象锁和类锁方法及代码块是不同步的。