划重点
static方法是类中的一个成员方法,属于整个类,即使不用创建任何对象也可以直接调用!
静态方法效率上要比实例化高,静态方法的缺点是不自动进行销毁,而实例化的则可以做销毁。
静态方法和静态变量创建后始终使用同一块内存,而使用实例的方式会创建多个内存。
在静态方法或者方法块上加的锁为 类锁 (锁类)
非静态方法为 对象锁(锁对象)
详细如下
类锁 (锁类):
public class StaticTest { public synchronized static void fun1() throws InterruptedException { for (int i = 0; i < 30; i++) { Thread.sleep(100); System.out.println("Static fun1 is running..."); } } public synchronized static void fun2() throws InterruptedException { for (int i = 0; i < 30; i++) { Thread.sleep(100); System.out.println("Static fun2 is running..."); } } public static void main(String[] args) { StaticTest staticTest1 = new StaticTest(); Thread t1 = new Thread(() -> { try { StaticTest.fun1(); } catch (InterruptedException e) { e.printStackTrace(); } }); StaticTest staticTest2 = new StaticTest(); Thread t2 = new Thread(() -> { try { StaticTest.fun2(); } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start();t2.start(); } }
会发现
会一直把一个fun 内容全部执行完 才会去执行另外一个fun的内容
对象锁:
public class StaticTest { public synchronized void fun1() throws InterruptedException { for (int i = 0; i < 30; i++) { Thread.sleep(100); System.out.println("Static fun1 is running..."); } } public synchronized void fun2() throws InterruptedException { for (int i = 0; i < 30; i++) { Thread.sleep(100); System.out.println("Static fun2 is running..."); } } public static void main(String[] args) { StaticTest staticTest1 = new StaticTest(); Thread t1 = new Thread(() -> { try { staticTest1.fun1(); } catch (InterruptedException e) { e.printStackTrace(); } }); StaticTest staticTest2 = new StaticTest(); Thread t2 = new Thread(() -> { try { staticTest2.fun2(); } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start();t2.start(); } }
不同对象的fun方法
出现交替打印 未锁住
public class StaticTest { public synchronized void fun1() throws InterruptedException { for (int i = 0; i < 30; i++) { Thread.sleep(100); System.out.println("Static fun1 is running..."); } } public synchronized void fun2() throws InterruptedException { for (int i = 0; i < 30; i++) { Thread.sleep(100); System.out.println("Static fun2 is running..."); } } public static void main(String[] args) { StaticTest staticTest1 = new StaticTest(); Thread t1 = new Thread(() -> { try { staticTest1.fun1(); } catch (InterruptedException e) { e.printStackTrace(); } }); StaticTest staticTest2 = new StaticTest(); Thread t2 = new Thread(() -> { try { staticTest1.fun2(); } catch (InterruptedException e) { e.printStackTrace(); } }); t1.start();t2.start(); } }
会发现
会一直把一个fun 内容全部执行完 才会去执行另外一个fun的内容 锁住了该对象