1700450289
1700450290
public void run(){
1700450291
1700450292
//增加CPU的繁忙程度,不用关心其逻辑含义
1700450293
1700450294
for(int i=0;i<1000;i++){
1700450295
1700450296
Math.hypot(Math.pow(92456789,i),Math.cos(i));
1700450297
1700450298
}
1700450299
1700450300
//自增运算
1700450301
1700450302
count++;
1700450303
1700450304
}
1700450305
1700450306
public int getCount(){
1700450307
1700450308
return count;
1700450309
1700450310
}
1700450311
1700450312
}
1700450313
1700450314
上面的代码定义了一个多线程类,run方法的主要逻辑是共享资源count的自加运算,而且我们还为count变量加上了volatile关键字,确保是从主内存中读取和写入的,如果有多个线程运行,也就是多个线程执行count变量的自加动作,count变量会产生脏数据吗?想想看,我们已经为count加上了volatile关键字呀!模拟多线程的代码如下:
1700450315
1700450316
public static void main(String[]args)throws Exception{
1700450317
1700450318
//理想值,并作为最大循环次数
1700450319
1700450320
int value=1000;
1700450321
1700450322
//循环次数,防止出现无限循环造成死机情况
1700450323
1700450324
int loops=0;
1700450325
1700450326
//主线程组,用于估计活动线程数
1700450327
1700450328
ThreadGroup tg=Thread.currentThread().getThreadGroup();
1700450329
1700450330
while(loops++<value){
1700450331
1700450332
//共享资源清零
1700450333
1700450334
UnsafeThread ut=new UnsafeThread();
1700450335
1700450336
for(int i=0;i<value;i++){
1700450337
1700450338
new Thread(ut).start();
[
上一页 ]
[ :1.700450289e+09 ]
[
下一页 ]