总览
- 多线程+对象在方法内部
- 多线程+对象在方法外部
- 多线程+单对象+synchronized
- 多线程+多对象+synchronized
- 多线程+synchronized+static
- 多线程+单对象+synchronized+static
- 多线程+多对象+synchronized+static
多线程+单对象+synchronized+static(例子)
Service类
public class Service {
synchronized public static void PrintA() {
try {
System.out.println("线程名称为:" + Thread.currentThread().getName() +
"在" + System.currentTimeMillis() + "进入printA");
Thread.sleep(3000);
System.out.println("线程名称为:" + Thread.currentThread().getName() +
"在" + System.currentTimeMillis() + "离开printA");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public static void printB() {
System.out.println("线程名称为:" + Thread.currentThread().getName() +
"在" + System.currentTimeMillis() + "进入printB");
System.out.println("线程名称为:" + Thread.currentThread().getName() +
"在" + System.currentTimeMillis() + "离开printB");
}
//注意这个方法不加static
synchronized public void printC() {
System.out.println("线程名称为:" + Thread.currentThread().getName() +
"在" + System.currentTimeMillis() + "进入printC");
System.out.println("线程名称为:" + Thread.currentThread().getName() +
"在" + System.currentTimeMillis() + "离开printC");
}
}
ThreadA.java
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service) {
this.service = service;
}
@Override
public void run() {
//注意这里是对象调用
service.PrintA();
}
}
ThreadB.java
public class ThreadB extends Thread {
private Service service;
public ThreadB(Service service) {
this.service = service;
}
@Override
public void run() {
//注意这里是对象调用
service.printB();
}
}
ThreadC.java
public class ThreadC extends Thread {
private Service service;
public ThreadC(Service service) {
this.service = service;
}
@Override
public void run() {
//注意这里是对象调用
service.printC();
}
}
Run.java
public class Run {
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();
}
}
运行结果
原理图(不同锁造成异步)
总结
-
异步的原因是因为持有不同的锁,一个是对象锁,一个是Class锁。而Class锁可以对类的所有对象实例起作用。
-
为了证明Class锁可以对类的所有对象实例起作用,下一篇使用多对象,就是多线程+多对象+synchronized+static的情况。