b、锁定一个对象或方法,它是静态的
这样锁定,它锁定的是对象所属的类
public synchronized    static void execute(){
      //...
}


等同于

public class TestThread {
    public static void execute(){
        synchronized(TestThread.class){
            //
          }
      }
}

测试:

目标类:

public class TestThread {
    private static Object lock=new Object();
    public synchronized static void execute(){  //同步静态方法
        for(int i=0;i<100;i++){
              System.out.println(i);
          }    
      }
    public static void execute1(){
        for(int i=0;i<100;i++){
              System.out.println(i);
          }    
      }
    public void test(){
          execute();     //输出是有序的,说明是同步的
        //execute1();  //输出是无须的,说明是异步的
      }
}


线程类:调用不同的方法,于是建立了两个线程类


public class ThreadA implements Runnable{
    public void run() {
          TestThread.execute();//调用同步静态方法
      }
}
public class ThreadB implements Runnable{
    public void run() {
          TestThread test=new TestThread();
          test.test();//调用非同步非静态方法
      }
}

调用:

Runnable runabbleA=new ThreadA();
Thread a=new Thread(runabbleA,"A");                
a.start();
Runnable runabbleB=new ThreadB();
Thread b=new Thread(runabbleB,"B");                
b.start();
评论
发表评论

您还没有登录,请登录后发表评论

wing929
搜索本博客
最近加入圈子
存档
最新评论