sundianzhe 2017-06-20 06:24 采纳率: 100%
浏览 2899
已采纳

java 多线程中每个线程中new一个对象使用还是有问题,各位大神帮忙看看,什么原理

-//代码如下,启动多个线程,每个线程线程中 new Test1 使用,但是在Test1 的方法中打印大概率中存在重复的输入,请问这是为什么?
package com;

import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Test2 {
public static void main(String[] args){
//System.out.println(System.getProperty("java.version"));
//System.out.println(Math.random());
final String xmlhead1="xmlhead1";
final String xmlbody1="xmlbody1";

 final String xmlhead2="xmlhead2";
 final String xmlbody2="xmlbody2";
ExecutorService exec = Executors.newCachedThreadPool(); 
final Semaphore semp = new Semaphore(5); 

for (int index = 0; index < 1000; index++) {
Runnable run = new Runnable() {
public void run() {
try {
// 获取许可
semp.acquire();
if(Math.random()>=(0.5)){
Test1 testone=new Test1();
//synchronized (testone){
testone.parseString(xmlhead1, xmlbody1);
//}
}
else{
Test1 testtwo=new Test1();
//synchronized (testtwo){
testtwo.parseString(xmlhead2, xmlbody2);
//}
}
semp.release();
}catch(Exception e){
e.printStackTrace();
}
}
};
exec.execute(run);
}
exec.shutdown();

}

}
class Test1 {
public String parseString(String head,String body){
System.out.println("parseString:"+this.toString());
return head+body;
}
}

  • 写回答

2条回答 默认 最新

  • 丵鹰 2017-06-20 07:02
    关注

    内存地址的分配与垃圾回收的,

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧