-//代码如下,启动多个线程,每个线程线程中 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;
}
}