新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Java多線程如何防止主線的阻塞
Java多線程在我們盡情的使用中存在著很多的問題,首先就是如何解決主線的阻塞問題??赐晗旅娴拇a希望你對(duì)此有所啟發(fā)。在不斷的學(xué)習(xí)中才能有更好的技術(shù)突破。Java多線程防止主線阻塞代碼如下:

- if(e.getSource()==startItem)
- {//運(yùn)行多線程爬蟲
- stateLabel.setText("運(yùn)行中....");
- try {
- URL url_url=new URL(web_url);
- web_host=url_url.getHost();
- } catch (MalformedURLException e2) {
- e2.printStackTrace();
- }
- if(tpool==null)
- {
- // System.out.println("運(yùn)行");
- new Thread(
- new Runnable(){
- public void run()
- {
- //要在另一個(gè)線程做得事情
- // System.out.println("啦啦啦啦");
- tpool=new ThreadPoolExecutor(minN,maxN,aliveT,
- TimeUnit.SECONDS,
- new LinkedBlockingQueue
()/*, - new ThreadPoolExecutor.CallerRunsPolicy()*/);
- //editor_pane.setText("創(chuàng)建線程池:
");- String tempstr="
" +- "創(chuàng)建線程池:" +
- "
設(shè)置最小線程數(shù)目:"+minN+- "
設(shè)置最大線程數(shù)目:"+maxN+- "
設(shè)置空閑線程存活時(shí)間(秒):"+aliveT+- "
設(shè)置阻塞線程隊(duì)列大小為:"+blockQN+- "
" +- "設(shè)置本地映射目錄為:" +
- "
"+dir_path+- "
" +- "
爬取入口網(wǎng)頁為:" +- "
"+web_url+"
";- setEditorContent(false,tempstr);
- addToUnProQ(web_url);
- String geturl=null;
- getPage gt=null;
- while((!isUnProQEmpty())||!tpool.isTerminated())
//有沒有處理的連接或者tpool沒有結(jié)束- {//如果 還有連接沒有被處理
- geturl=delFromUnProQ();
- if(geturl!=null)
- {
- addToProQ(geturl);
- gt=new getPage(geturl);
- tpool.execute(gt);
- }
- try {//等待0.2秒 以便在隊(duì)列中能夠有更多的鏈接
- Thread.sleep((long)(Math.random()*200));
- } catch (InterruptedException e1) {
- e1.printStackTrace();
- }
- }
- tpool.shutdown();
- tpool=null;
- stateLabel.setText("歡迎使用本網(wǎng)站結(jié)構(gòu)分析軟件");
- //setEditorContent(true,shuoming);
- }
- }).start();
- }
- else
- {
- showMessageBox("已經(jīng)開始運(yùn)行了..不要亂按了.
閑得慌就到www.51cto.com網(wǎng)站看文章去吧..");- String comd = "explorer http://www.blesslucky.com/";
- try {
- Runtime.getRuntime().exec(comd);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- }
以上就是對(duì)Java多線程代碼的相關(guān)介紹,希望大家有所收獲。
分享標(biāo)題:Java多線程如何防止主線的阻塞
URL鏈接:http://fisionsoft.com.cn/article/dhgocgi.html


咨詢
建站咨詢
