JVM类加载过程

类加载过程大致如上图,关于初始化贴一段代码

public class ClassLoadTest2 {
public static int time = 0;
static{
Thread t = new Thread(new Runnable(){
public void run(){
do{
time++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}while(true);
}});
t.start();
}
}

public class ClassLoadTest {
public static int time = 0;
static{
Thread t = new Thread(new Runnable(){
public void run(){
do{
time++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}while(true);
}});
t.start();
}

public static void main(String[] args) throws InterruptedException {
Thread.sleep(5000);
System.out.println(ClassLoadTest.time);
System.out.println(ClassLoadTest2.time);
Thread.sleep(5000);
System.out.println(ClassLoadTest.time);
System.out.println(ClassLoadTest2.time);
}
}

运行main方法后,输出为5,0,10,5(也可能为6,0,11,5)
在执行main方法时,ClassLoadTest编译,加载,验证和初始化立即执行,这个速度的快慢会导致输出的结果不同
在执行main方法第三句是,ClassLoadTest2加载
这两个类的静态方法里有对各自静态变量time的修改,当类加载后time的值会不停的增加。

只是作为举例,实际中千万不能这么写代码,这是我看到我们的外包写的。。。这个代码不仅消耗了额外的性能,而且没有做单例,发布不安全,值会出错(当然,一秒加一是等不到出错了),还无法被jvm回收,总之问题多多,绝对不能这么写

 

转载于:https://www.cnblogs.com/codingcheng/p/10701776.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值