十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
Java多线程在我们尽情的使用中存在着很多的问题,首先就是如何解决主线的阻塞问题。看完下面的代码希望你对此有所启发。在不断的学习中才能有更好的技术突破。Java多线程防止主线阻塞代码如下:

- if(e.getSource()==startItem)
 - {//运行多线程爬虫
 - stateLabel.setText("运行中....");
 - try {
 - URL url_url=new URL(web_url);
 - web_host=url_url.getHost();
 - } catch (MalformedURLException e2) {
 - e2.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
 ()/*, - new ThreadPoolExecutor.CallerRunsPolicy()*/);
 - //editor_pane.setText("创建线程池:
 
");- String tempstr="
 
" +- "创建线程池:" +
 - "
 
设置最小线程数目:"+minN+- "
 
设置最大线程数目:"+maxN+- "
 
设置空闲线程存活时间(秒):"+aliveT+- "
 
设置阻塞线程队列大小为:"+blockQN+- "
 
" +- "设置本地映射目录为:" +
 - "
 
"+dir_path+- "
 
" +- "
 
爬取入口网页为:" +- "
 
"+web_url+"
";- 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 {//等待0.2秒 以便在队列中能够有更多的链接
 - Thread.sleep((long)(Math.random()*200));
 - } catch (InterruptedException e1) {
 - e1.printStackTrace();
 - }
 - }
 - tpool.shutdown();
 - tpool=null;
 - stateLabel.setText("欢迎使用本网站结构分析软件");
 - //setEditorContent(true,shuoming);
 - }
 - }).start();
 - }
 - else
 - {
 - showMessageBox("已经开始运行了..不要乱按了.
 
闲得慌就到www.51cto.com网站看文章去吧..");- String comd = "explorer http://www.blesslucky.com/";
 - try {
 - Runtime.getRuntime().exec(comd);
 - } catch (IOException e1) {
 - e1.printStackTrace();
 - }
 - }
 - }
 
以上就是对Java多线程代码的相关介绍,希望大家有所收获。