62,612
社区成员
发帖
与我相关
我的任务
分享
for (int i = 0; i < threadNum; i++)
{
Thread t = new WorkThread(apiName, param);
t.start();
}
// textArea.setText();
while(true)
{
if(!WorkThread.hasThreadRunning())
{
textArea.append("花费的时间为:" +(System.currentTimeMillis()-formerTime)+" millsecond \n");
break;
}
}
public static boolean hasThreadRunning()
{
return (runningThreads.size()>0);
}
public class WorkThread extends Thread{
private static List<Thread> runningThreads = new ArrayList<Thread>();
private ITest apiClass ;
private int numberOfOperation;
private CountDownLatch cdl;
public WorkThread(String apiName, Map<String,Object> param,CountDownLatch cdl) throws Exception
{
apiClass = (ITest)(Class.forName(apiName).newInstance());
apiClass.set(param);
this.numberOfOperation = Integer.parseInt(((String)param.get("numberOfOperation")));
this.cdl = cdl;
}
public void regist(Thread t)
{
synchronized (runningThreads) {
runningThreads.add(t);
}
}
public void unregist(Thread t)
{
synchronized (runningThreads) {
runningThreads.remove(t);
}
}
public static boolean hasThreadRunning()
{
return (runningThreads.size()>0);
}
public void run()
{
regist(this);
cdl.countDown();
for(int i = 0 ; i<numberOfOperation; i++)
{
apiClass.run();
}
unregist(this);
apiClass.release();
}
}
修改后的调用代码:
CountDownLatch cdl = new CountDownLatch(1);
for (int i = 0; i < threadNum; i++)
{
Thread t = new WorkThread(apiName, param,cdl);
t.start();
}
cdl.await();
// textArea.setText();
while(true)
{
if(!WorkThread.hasThreadRunning())
{
textArea.append("花费的时间为:" +(System.currentTimeMillis()-formerTime)+" millsecond \n");
break;
}
}
public class WorkThread extends Thread{
private static List<Thread> runningThreads = new ArrayList<Thread>();
private ITest apiClass ;
private int numberOfOperation;
public WorkThread(String apiName, Map<String,Object> param) throws Exception
{
apiClass = (ITest)(Class.forName(apiName).newInstance());
apiClass.set(param);
this.numberOfOperation = Integer.parseInt(((String)param.get("numberOfOperation")));
}
public void regist(Thread t)
{
synchronized (runningThreads) {
runningThreads.add(t);
}
}
public void unregist(Thread t)
{
synchronized (runningThreads) {
runningThreads.remove(t);
}
}
public static boolean hasThreadRunning()
{
return (runningThreads.size()>0);
}
public void run()
{
regist(this);
for(int i = 0 ; i<numberOfOperation; i++)
{
apiClass.run();
}
unregist(this);
apiClass.release();
}
}