您的位置:首页 > 其它

2.2.9同步静态方法与synchronized(class)

2017-10-11 23:52 447 查看
package cha02.execise22;

/**
* Created by sunyifeng on 17/9/26.
*/
public class Service {
// 打印方法A
synchronized public static void printA(){
try {
System.out.println("进入方法printA,线程名称:" + Thread.currentThread().getName());
Thread.sleep(3000);
System.out.println("离开方法printA,线程名称:" + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// 打印方法B
synchronized  public static void  printB(){
System.out.println("进入方法printB,线程名称:" + Thread.currentThread().getName());
System.out.println("离开方法printB,线程名称:" + Thread.currentThread().getName());
}
}

package cha02.execise22;

/**
* Created by sunyifeng on 17/9/26.
*/
public class ThreadA extends Thread {
@Override
public void run() {
//
Service.printA();
}
}

package cha02.execise22;

/**
* Created by sunyifeng on 17/9/26.
*/
public class ThreadB extends Thread {
@Override
public void run() {
//
Service.printB();
}
}

package cha02.execise22;

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

运行结果:

进入方法printA:A

离开方法printA:A

进入方法printB:B

离开方法printB:B

程序分析:

同步静态方法是对该类的锁定。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐