日期:2014-05-20  浏览次数:20733 次

~~~~~~~~~~~~~~~~~请大家帮我优化开启线程的思路~~~~~~~~~~~~~
CrawlWebData   objCrawlWebData   =   new   CrawlWebData();

//最多允许开5个线程,由于要用到join方法,因此采用下面的做法
Thread   t1;   Thread   t2;   Thread   t3;   Thread   t4;   Thread   t5;

switch(objConfigMeta_B.getMaxAllowThreadNum())
{
case   1:
t1   =   new   Thread(objCrawlWebData);   t1.start();   t1.join();
break;
case   2:
t1   =   new   Thread(objCrawlWebData);   t1.start();   t1.join();   t2   =   new   Thread(objCrawlWebData);   t2.start();   t2.join();  
break;
case   3:
t1   =   new   Thread(objCrawlWebData);   t1.start();   t1.join();   t2   =   new   Thread(objCrawlWebData);   t2.start();   t2.join();   t3   =   new   Thread(objCrawlWebData);   t3.start();   t3.join();  
break;
case   4:
t1   =   new   Thread(objCrawlWebData);   t1.start();   t1.join();   t2   =   new   Thread(objCrawlWebData);   t2.start();   t2.join();   t3   =   new   Thread(objCrawlWebData);   t3.start();   t3.join();   t4   =   new   Thread(objCrawlWebData);   t4.start();   t4.join();
break;
case   5:
t1   =   new   Thread(objCrawlWebData);   t1.start();   t1.join();   t2   =   new   Thread(objCrawlWebData);   t2.start();   t2.join();   t3   =   new   Thread(objCrawlWebData);   t3.start();   t3.join();   t4   =   new   Thread(objCrawlWebData);   t4.start();   t4.join();   t5   =   new   Thread(objCrawlWebData);   t5.start();   t5.join();
break;
default:
System.out.println( "==========Unallowed   thread   number   "   +   objConfigMeta_B.getMaxThreadNum()   +   "========== ");
System.exit(1);
}
CrawlWebData   是一个实现了Runnable接口的类.
如果不是需要用到join,我就直接这样写了:
for(int   j=0;   j <objConfigMeta_B.getMaxAllowThreadNum();   j++)
{
new   Thread(objCrawlWebData).start();
}
既简单,又方便.
但是现在需要主线程等待上面的线程结束后才能接着往下走,我觉得我上面的写法实在太笨拙,不知道有没有更好的办法,我知道JAVA有一个动态编译的方法,但是我不太懂.

------解决方案--------------------
for(int j=0; j <objConfigMeta_B.getMaxAllowThreadNum(); j++)
{
Thread t = new Thread(objCrawlWebData);
t.start();
t.join();
}

------解决方案--------------------
不是重复定义变量,而是这个变量的生存期就到单次for循环结束。