Date().getTime()线程堵塞问题

来源:互联网 发布:java中方法的签名 编辑:程序博客网 时间:2024/04/30 23:13

new Date().getTime()出现线程堵塞的问题概率比较低,但是一旦出现,那么性能也将下降很多,下面代码可以测试这个问题,创建10个线程,不断执行。

其堵塞原因在于这个方法引用了getJulianCalendar(),

    synchronized private static final BaseCalendar getJulianCalendar() {
if (jcal == null) {
   jcal = (BaseCalendar) CalendarSystem.forName("julian");
}
return jcal;
    }


测试代码:

public class DuMain {public static void main(String[] args) {long time = System.currentTimeMillis();test();long end = System.currentTimeMillis();System.out.println(end - time);//................for(int i=0;i<10;i++){new Thread(){@Overridepublic void run() {for(int i=0;i<1000000000;i++){test();//System.out.println(i);}}}.start();}for(int i=0;i<1000000000;i++){time = System.currentTimeMillis();test();end = System.currentTimeMillis();System.out.println(""+i+"--"+(end - time));//System.out.println(i);}}public static boolean test() {Date begin = new Date();int ONE_SECOND = 2;boolean result = false;while (true) {if (new Date().getTime() - begin.getTime() >= ONE_SECOND) {result = true;break;}}return result;}}



result:

....

11423--2
11424--274
11425--2
11426--3

....


可以看到运行到一定次数的时候就会被阻塞一下


全聚合站点

原创粉丝点击