synchronized关键字与对象锁

来源:互联网 发布:c语言实现面向对象 编辑:程序博客网 时间:2024/06/05 16:54

1、创建Service类,printA()和printB()为synchronized静态方法,printC()为synchronized方法

public class Service {
synchronized publicstatic 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 (Exception e) {
e.printStackTrace();
}
}

synchronized public static void printB(){
try {
System.out.println("线程名称:"+Thread.currentThread().getName()+
"在"+System.currentTimeMillis()+"进入printB");
Thread.sleep(3000);
System.out.println("线程名称:"+Thread.currentThread().getName()+
"在"+System.currentTimeMillis()+"离开printB");
} catch (Exception e) {
e.printStackTrace();
}
}

synchronized public void printC(){
try {
System.out.println("线程名称:"+Thread.currentThread().getName()+
"在"+System.currentTimeMillis()+"进入printC");
Thread.sleep(3000);
System.out.println("线程名称:"+Thread.currentThread().getName()+
"在"+System.currentTimeMillis()+"离开printC");
} catch (Exception e) {
e.printStackTrace();
}
}
}


2、分别定义三个线程类ThreadA,ThreadB,ThreadB 在run方法中分别调用同一个对象的printA(),printB(),printC()

public class ThreadA extends Thread{
private Service service;

public ThreadA(Service service) {
this.service = service;
}

@Override
public void run() {
service.printA();
}
}


public class ThreadB extends Thread{
private Service service;

public ThreadB(Service service) {
this.service = service;
}

@Override
public void run() {
service.printB();
}
}


public class ThreadC extends Thread{
private Service service;

public ThreadC(Service service) {
this.service = service;
}

@Override
public void run() {
service.printC();
}
}

3、在main方法中运行

public static void main(String[] args) {

Service service = new Service();
ThreadA a = new ThreadA(service);
a.setName("A");

ThreadB b = new ThreadB(service);
b.setName("B");

ThreadC c = new ThreadC(service);
c.setName("C");

a.start();
b.start();
c.start();
}

4.打印结果

线程名称:C在1495550933354进入printC
线程名称:A在1495550933354进入printA
线程名称:C在1495550936357离开printC
线程名称:A在1495550936357离开printA
线程名称:B在1495550936357进入printB
线程名称:B在1495550939359离开printB



我们可以看出A,B是顺序执行的,C是异步执行的。原因是他们持有不同的锁,A,B持有Class锁,C持有对象锁