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

来源:互联网 发布:c语言的头文件是什么 编辑:程序博客网 时间:2024/05/17 16:15

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

程序分析:

同步静态方法是对该类的锁定。

阅读全文
0 0
原创粉丝点击