您的位置:首页 > 其它

2.2.9同步静态方法和synchronized(class)效果一样

2017-10-12 00:19 645 查看
package cha02.execise25;

/**
* Created by sunyifeng on 17/9/27.
*/
public class Service {
public static void printA() {
synchronized (Service.class) { // FIXME: 注意这里
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();
}
}
}

public static void printB() {
synchronized (Service.class) {  // FIXME: 注意这里
System.out.println("进入方法printB,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
System.out.println("离开方法printB,线程名称:" + Thread.currentThread().getName() + ",当前时间" + System.currentTimeMillis());
}
}
}


package cha02.execise25;

/**
* 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.execise25;

/**
* 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.execise25;

/**
* Created by sunyifeng on 17/9/27.
*/
public class Run {
public static void main(String[] args) {
Service service1 = new Service();
Service service2 = new Service();
//
ThreadA threadA = new ThreadA(service1);
threadA.setName("A");
threadA.start();
//
ThreadB threadB = new ThreadB(service2);
threadB.setName("B");
threadB.start();
}
}

运行结果:

进入方法printA,线程名称:A,当前时间1507738817656

离开方法printA,线程名称:A,当前时间1507738822660

进入方法printB,线程名称:B,当前时间1507738822660

离开方法printB,线程名称:B,当前时间1507738822660
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐