package cha02.execise23;
/**
* Created by sunyifeng on 17/9/27.
*/
public class Service {
// 静态方法A
synchronized public static void printA() {
try {
System.out.println("进入方法printA,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
Thread.sleep(5000);
System.out.println("离开方法printA,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 静态方法B
synchronized public static void printB() {
System.out.println("进入方法printB,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
System.out.println("离开方法printB,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
}
// 实例方法C
synchronized public void printC() {
System.out.println("进入方法printC,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
System.out.println("离开方法printC,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
}
}
package cha02.execise23;
/**
* Created by sunyifeng on 17/9/27.
*/
public class ThreadA extends Thread {
private Service service;
public ThreadA(Service service) {
super();
this.service = service;
}
@Override
public void run(){
service.printA(); //
}
}
package cha02.execise23;
/**
* Created by sunyifeng on 17/9/27.
*/
public class ThreadB extends Thread {
private Service service;
public ThreadB(Service service) {
super();
this.service = service;
}
@Override
public void run() {
service.printB();//
}
}
package cha02.execise23;
/**
* Created by sunyifeng on 17/9/27.
*/
public class ThreadC extends Thread {
private Service service;
public ThreadC(Service service) {
super();
this.service = service;
}
@Override
public void run() {
service.printC(); //
}
}
package cha02.execise23;
/**
* Created by sunyifeng on 17/9/27.
*/
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();
}
}
运行结果:
进入方法printA,线程名称:A,当前时间1507737435167
进入方法printC,线程名称:C,当前时间1507737435169
离开方法printC,线程名称:C,当前时间1507737435170
离开方法printA,线程名称:A,当前时间1507737440171
进入方法printB,线程名称:B,当前时间1507737440171
离开方法printB,线程名称:B,当前时间1507737440172
程序分析:
1、三个线程是异步执行的,线程A、线程B同步执行,线程C异步执行;
2、线程A、线程B持有的是class锁,线程C持有的是对象锁。