关于静态代码块的

package com.zcd;

public class StaticCode
{
    public static void main(String[] args)
    {
        System.out.println("进入主方法");
        StaticCode sc = new StaticCode();
        sc = new StaticCode();
    }
    
    public StaticCode()
    {
        System.out.println("无参构造方法");
    }
    
    {
        System.out.println("代码块1");
    }
    
    {
        System.out.println("代码块2");
    }
    
    static{
        System.out.println("静态代码块1");
    }
    
    static{
        System.out.println("静态代码块2");
    }
}

执行结果如下:

结论:

  ①、静态代码块是在Java虚拟机加载类的时候执行的。所以静态代码要比类的主方法还要先执行。而且,不管为该类创建多少个对象,静态代码块只执行一次。

  ②、非静态代码块是在创建类的时候执行的,注意主方法在非静态代码块之前执行的。

一个类中有静态同步方法和非静态同步方法,静态同步方法与非静态同步方法之间是不会有竞态条件。锁的是两个对象,一个锁的是类,一个锁的是类的对象。所以不会影响。

下面贴一个例子:

package com.zcd;

public class ThreadTest4
{
    public static void main(String[] args)
    {
        Example example = new Example();
        
        TheThread1 t1 = new TheThread1(example);

        example = new Example();//如果把这句注释掉,变成一个对象两个线程,还是打印乱序。
        
        TheThread2 t2 = new TheThread2(example);
        
        t1.start();
        t2.start();
    }
}

class Example
{
    static{
        System.out.println("静态代码块1");
    }
    
    static{
        System.out.println("静态代码块2");
    }
    
    public synchronized void execute1()
    {
        for(int i = 0; i < 50; i++)
        {
            System.out.println("example: " + i);
        }
    }
    
    public static synchronized void execute2()
    {
        for(int i = 0; i < 50; i++)
        {
            System.out.println("example: " + i);
        }
    }
}

class TheThread1 extends Thread
{
    private Example example;
    
    public TheThread1()
    {
        
    }
    
    public TheThread1(Example example)
    {
        this.example = example;
    }
    
    @Override
    public void run()
    {
        this.example.execute1();
    }
}

class TheThread2 extends Thread
{
    private Example example;
    
    public TheThread2()
    {
        
    }
    
    public TheThread2(Example example)
    {
        this.example = example;
    }
    
    @Override
    public void run()
    {
        this.example.execute2();
    }
}

 

posted @ 2017-10-06 20:56  钓鱼翁  阅读(309)  评论(0编辑  收藏  举报