关键字synchronized还可以应用在static静态方法上,如果这样写,那是对当前的*.java文件对应的Class类进行持锁。
package synStaticMethod; /** * Created by Administrator on 2017/1/22 0022. */ public class Service { synchronized public static void printA(){ try{ System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"进入printA"); Thread.sleep(3000); System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"离开printA"); } catch (InterruptedException e) { e.printStackTrace(); } } synchronized public static void printB(){ System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"进入printB"); System.out.println("线程名称为:"+Thread.currentThread().getName()+"在"+System.currentTimeMillis()+"离开printB"); } }
package synStaticMethod; /** * Created by Administrator on 2017/1/22 0022. */ public class ThreadA extends Thread{ public void run(){ Service.printA(); } }
package synStaticMethod; /** * Created by Administrator on 2017/1/22 0022. */ public class ThreadB extends Thread { public void run(){ Service.printB(); } }
package synStaticMethod; /** * Created by Administrator on 2017/1/22 0022. */ 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(); } }
线程名称为:A在1485063366543进入printA
线程名称为:A在1485063369543离开printA
线程名称为:B在1485063369543进入printB
线程名称为:B在1485063369543离开printB
从结果来看,是同步的效果,和将synchronized关键字加到非静态方法上使用的效果是一样的,其实synchronized关键字加到static静态方法上是给Class类上锁,而synchronized关键字加到非static静态方法上是给对象加锁。