Java线程同步之静态方法

静态方法是同步方法:自动加锁,锁的对象是类对象

public static void main(String[] args) {
        Thread [] threadArr=new Thread[10];
        for (Thread item:threadArr)
        {
            item=new Thread(){
                @Override
                public void run()
                {

                    try {
                        int num = Employee.setNum();
                        System.out.println(String.format("线程:%d的Num值是%d",super.getId(),num));
                    }
                    catch (Exception ex){

                    }
                }
            };
            item.start();

        }
        try{
            System.in.read();
        }
        catch (Exception ex)
        {

        }
}
class Employee {

 static {
        num=0;
    }

   static int num;

    public static int getNum()
    {
        return num;
    }

    public static int setNum()
    {
        num ++;
        return getNum();
    }
}

 

线程:19的Num值是7
线程:15的Num值是2
线程:13的Num值是1
线程:18的Num值是9
线程:14的Num值是8
线程:22的Num值是10
线程:17的Num值是3
线程:16的Num值是4
线程:21的Num值是6
线程:20的Num值是5

 

posted @ 2017-02-15 17:38  zslm___  阅读(372)  评论(0编辑  收藏  举报