Here is the sample which i was working
Thread[] TCreate = new Thread[sexDataSize];
for(int i=0;i<sexData.size();i++)
{
final SDISQueryBuilder _qryBulider=qryBulider;
final String _newQry=_qryBulider.getQueryStringOnSex(sexData.get(i).getName(), baseQry, SDISCommonParam.onSEXID,sdisQueryInfo);
final int _i = i;
TCreate[i] = new Thread(new Runnable() {
public void run()
{
groupData.add("GROUPID_"+(_i+1), ((List<Count>) _qryBulider.facetOn_FieldName(_newQry.replace("1028","1046" ), SDISQueryInfo.url3, SDISCommonParam.onGroupID).getValues()));
}});
TCreate[i].setName("GROUPID_"+(_i+1));
TCreate[i].start();
}
for(int i=0;i<sexData.size();i++)
while (TCreate[i].isAlive()) Thread.sleep(10);
I need to know the difference between Thread.sleep(开发者_JAVA百科10) and TCreate[i].sleep(10) . Is both are same? Any other issues lies in this? And whether i am handling the thread properly. Let me know if there is change. Thanks in advance
'Thread.sleep()'
is a static method, which means, it execution is not dependent on an instance it called on. In other words 'myThread.sleep()'
means the same as 'otherThread.sleep()'
if both that objects are the instances of 'Thread'
class
No matter what object you give the
Thread.sleep(millis);
method it is the same as
Thread.currentThread().sleep();
You cannot make another thread sleep this way. Instead you need to have a shared resource the threads checks or waits on and your controlling thread makes that resource unavailable.
Thread.sleep(10) will sleep the currently executing thread, i.e. not necessarily one of the threads you have in your array, more likely the main thread that spawns the others looking at your example, because it's from that thread you call it.
If what you want to achieve is to make your spawning process wait until all it's childs have finished working, then Java provides a built in mechanism for this, namely the join method. What it does is to make the thread wherein you make the call wait until the thread on which you call it finishes. If this is indeed what you want to achieve, then replace your last for-loop with the following:
for(Thread t : TCreate){ //Consider naming variables with initial lowercase
t.join();
//Should be called after it's been started but not until you have started all of them
}
//Execution resumes here when all spawned threads have completed their task.
I hope this made it clearer.
精彩评论