静态方法是同步方法:自动加锁,锁的对象是类对象
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
原文:http://www.cnblogs.com/zhshlimi/p/6402457.html