多线程阻塞 Java多线程如何防止主线的阻塞
Java多线程如何防止主线的阻塞
Java多线程在我们尽情的使用中存在着很多的问题 首先就是如何解决主线的阻塞问题 看完下面的代码希望你对此有所启发 在不断的学习中才能有更好的技术突破 Java多线程防止主线阻塞代码如下
if(e getSource()==startItem)
{//运行多线程爬虫
stateLabel setText( 运行中 );
try {
URL url_url=new URL(web_url);
web_host=url_url getHost();
} catch (MalformedURLException e ) {
e printStackTrace();
}
if(tpool==null)
{
// System out println( 运行 );

new Thread(
new Runnable(){
public void run()
{
//要在另一个线程做得事情
// System out println( 啦啦啦啦 );
tpool=new ThreadPoolExecutor(minN maxN aliveT
TimeUnit SECONDS
new LinkedBlockingQueue<Runnable>());
//editor_pane setText( 创建线程池:<br> );
String tempstr= <hr> +
创建线程池: +
<br>设置最小线程数目 +minN+
<br>设置最大线程数目 +maxN+
<br>设置空闲线程存活时间(秒) +aliveT+
<br>设置阻塞线程队列大小为 +blockQN+
<hr> +
设置本地映射目录为 +
<br> +dir_path+
<hr> +
<br>爬取入口网页为 +
<br> +web_url+ <hr> ;
setEditorContent(false tempstr);
addToUnProQ(web_url);
String geturl=null;
getPage gt=null;
while((!isUnProQEmpty())||!tpool isTerminated())
//有没有处理的连接或者tpool没有结束
{//如果 还有连接没有被处理
geturl=delFromUnProQ();
if(geturl!=null)
{
addToProQ(geturl);
gt=new getPage(geturl);
tpool execute(gt);
}
try {//等待 秒 以便在队列中能够有更多的链接
Thread sleep((long)(Math random()* ));
} catch (InterruptedException e ) {
e printStackTrace();
}
}
tpool shutdown();
tpool=null;
stateLabel setText( 欢迎使用本网站结构分析软件 );
//setEditorContent(true shuoming);
}
}) start();
}
else
{
showMessageBox( 已经开始运行了 不要乱按了
闲得慌就到网站看文章去吧 );
String d = explorer ;
try {
Runtime getRuntime() exec(d);
} catch (IOException e ) {
e printStackTrace();
}
}
}
lishixinzhi/Article/program/Java/gj/201311/27572