线程很不懂,求帮助
这是
public static int checkURL(URL url){...}
class Worker implements Runnable {
  private BlockingQueue<URL> queue;
  public Worker(BlockingQueue<URL> q){
  this.queue = q;
  }  public void run() {
  for(URL url = q.poll(); url != null;){
  int retcode = checkURL(url);
  ...
  }
  }
}BlockingQueue<URL> urls = ...;
new Thread(new Worker(urls)).start();
new Thread(new Worker(urls)).start();
别人给的思路

解决方案 »

  1.   


    首先是用正则表达式去判断,这个链接是否合法,例如链接的名字..后缀名之类的..其次,判断是否是死链接的话,再用Java去Connection一下,如果返回异常或者是连不上的话,那很大可能就是死链接了.
      

  2.   


    public class ThreadUrl { /**
     * @param args
     */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
    BlockingQueue<URL> urls = new ArrayBlockingQueue<URL>(1);
    urls.add(new URL("http://www.baidu.com")); // 每次往queue中送入的URL不同就不会重复了
    new Thread(new Worker(urls)).start();
    new Thread(new Worker(urls)).start();
    } catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    } public static int checkURL(URL url) {
    return 1;
    }
    }class Worker implements Runnable {
    private BlockingQueue<URL> queue; public Worker(BlockingQueue<URL> q) {
    this.queue = q;
    } public void run() {

    // 这里可以写一个检查程序queue是否为空。。不为空就唤醒线程。。

    for (URL url = queue.poll(); url != null;) { // 这个循环改一下不然会死循环
    int retcode = ThreadUrl.checkURL(url); // 这里检查URL死链接
    System.out.println("检查结果:" + retcode);

    // 将成功的连接返回去
    }

    // 检查完以后可以线程等待或者睡眠。。将queue中检查过的清空
    // 线程一直执行的话。。会消耗资源
    }
    }
      

  3.   

    (URL url = queue.poll(); url != null;
    看不懂啊
      

  4.   

    queque.poll();方法:Retrieves and removes the head of this queue, or null if this queue is empty.不会陷入死循环。
    jdk文档的例子:class Producer implements Runnable {
       private final BlockingQueue queue;
       Producer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while(true) { queue.put(produce()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       Object produce() { ... }
     } class Consumer implements Runnable {
       private final BlockingQueue queue;
       Consumer(BlockingQueue q) { queue = q; }
       public void run() {
         try {
           while(true) { consume(queue.take()); }
         } catch (InterruptedException ex) { ... handle ...}
       }
       void consume(Object x) { ... }
     } class Setup {
       void main() {
         BlockingQueue q = new SomeQueueImplementation();
         Producer p = new Producer(q);
         Consumer c1 = new Consumer(q);
         Consumer c2 = new Consumer(q);
         new Thread(p).start();
         new Thread(c1).start();
         new Thread(c2).start();
       }
     }
      

  5.   

     
    while(true) {  
                    // wait for a random time  
                  //  Thread.sleep((int) (Math.random() * 3000));  
       try {
       URL u;
       u=queue.take();
      
       int retcode = checkURL(u);
       System.out.println(m+Thread.currentThread().getName()+"线程"+retcode+"连接地址"+ u);
       m++;
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block

    e.printStackTrace();
    }  
                }  如何写能跳出循环
      

  6.   

    class Worker implements Runnable {

      private BlockingQueue<URL> queue;
      public Worker(BlockingQueue<URL> q){
      this.queue = q;
      }
         public void run()  {
     
    // while(true) {  
                    // wait for a random time  
                  //  Thread.sleep((int) (Math.random() * 3000));  
       try {
       URL u;
       u=queue.take();
      
       int retcode = checkURL(u);
       System.out.println(m+Thread.currentThread().getName()+"线程"+retcode+"连接地址"+ u);
       m++;
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block

    e.printStackTrace();
    }  
    我写的一直不会停止,应该如何写
      

  7.   

    不要用take,用poll。take
    Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.Returns:
        the head of this queuepoll
    Retrieves and removes the head of this queue, or returns null if this queue is empty.

    Returns:
        the head of this queue, or null if this queue is empty
      

  8.   

       for (URL url = queue.poll(); url != null;) { // 这个循环改一下不然会死循环
                int retcode = ThreadUrl.checkURL(url); // 这里检查URL死链接
                System.out.println("检查结果:" + retcode);
                
                // 将成功的连接返回去
            }循环如何改啊。
    基本上不懂线程,现在让我写真悲剧啊
      

  9.   


    我的一个线程方法。。你看看然后自己修改一下public class ThreadChangeProperties {

    public ThreadChangeProperties(){}

    private Logger logger = Logger.getLogger(ThreadChangeProperties.class);   // 定义一个线程锁,保证当前只有一个工作在操作中     
     private final Object lock = new Object();         
     // 定义一个Thread变量      
     private Thread thread;         
     // 控制线程循环的开关       
     private boolean active = true;         
     // 定义一个毫秒级的时间变量,指示何时执行下一个操作  (30秒)   
     private long interval=30000; 
     //指定一个文件
     // private File file=new File("C:\\Program Files (x86)\\IDtrust\\server\\etc\\kouyi.properties");
     
     /**      
      *  
      * *定义个一个抽象的方法用来获取下一个执行操作的时间,可使用NEVER       
      * */      
     protected final static long NextTime=2000; 
     
     protected String getName()       
     {           
     return getClass().getName();         
     }      
     
     /*
      * *       
      * 
      * 启动线程       
      * */      
     public void start(final File file)      
     {           
     thread = new Thread(new Runnable()           
     {               
     public void run()               
     {                  
     runInternal(file);               
     }           
     }, getName());           
     
     thread.start();       
     }  
     
     /**       
      * 
      * * 强迫停止线程,跳出for循环      
      *  */      
     public void stop() throws InterruptedException       
     {           
     synchronized (lock)           
     {               
     active = false;               
     lock.notify();
     logger.debug("exception encountered was forced to stop the thread");
     }           
     thread.join();       
     }   
     
     /**       
      * * 此方法可以在任何时候激活当前线程,让线程进入工作执行环节      
      *  
      *  */     
     
     public void workAdded(long time)       
     {           
     synchronized (lock)           
     {               
     if (time>0)               
     {                   
     // 立刻激活线程工作继续运行                 
     lock.notify();
     logger.debug("thread is forced to activate");
    }           
    }       
    }      
     
     /**       
      * 
      * * 线程监控属性文件更新      
      *  
      * */      
     private void runInternal(File file1)       
     {        
     int j=0;
     long filetemplasttime=0;
     File file=file1;
     // 无限循环           
     for (;;)          
     {               
     // 截获Exception,以保证线程不会因此而中断              
     try              
     {                   
     synchronized (lock)                   
     {                                            
     // 获得时间区间,即要等待的时间段                                      
     if (interval > 0)                       
     {                          
     try                         
     {    
     lock.wait(interval); 
     logger.debug("thread was waiting for 30 second");
     }                          
     catch (InterruptedException e)                           
     {                               
     // 忽略此Exception 
     logger.debug("thread waiting for anomalies encountered");
     }                       
     }                       
     // 如果active为false,强制中断                       
     if (!active)                       
     {                           
     break;                       
     }                   
     }                   
     // 执行具体的工作
     long filelasttime=file.lastModified();
     if(j==0){
     filetemplasttime=file.lastModified();
     logger.debug("Start the thread monitor properties file success, init lastModified properties file"); 
     }else{
     if(filetemplasttime!=filelasttime){
     logger.debug("properties file has been updated time("+new Date(filelasttime).toLocaleString()+")");
     filetemplasttime=filelasttime;
     try{
     // 初始化radius服务
     Radius.initRefreshProperties(new String[0], ((ProtectedProperties) (null)));
     logger.debug("initRefreshProperties load client machine for radius auth is success");
     }catch(Exception ex){
     logger.debug("initRefreshProperties load client machine is fail");
     }
     
     }else{
     //logger.debug("属性文件没有任何更新"); 
     }
     } 
     j++;
    }               
    catch (Throwable t)               
    {                   
     try                  
     {                       
     Thread.sleep(10000);
     logger.debug("read properties file updated encountered exception, the thread sleep 10 seconds");
     }                   
     catch (InterruptedException ie)                 
     {                       
     // 忽略此Exception                   
    }              
    }           
    }       
     }
     
     public static void main(String args[]) {
    File file=new File("C:\\Program Files (x86)\\IDtrust\\server\\etc\\kouyi.properties");
    new ThreadExample().start(file);
     }
    }
      

  10.   

    for循环的第三项忘写了
                for (URL url = queue.poll(); url != null; url = queue.poll()) 
      

  11.   

    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.SocketTimeoutException;
    import java.net.URL;
    import java.util.concurrent.BlockingQueue;
    import java.util.concurrent.LinkedBlockingQueue;public class BookChecker {    public static void main(final java.lang.String[] args) throws Exception {
            BlockingQueue<URL> urls = new LinkedBlockingQueue<URL>();
            urls.add(new URL("http://www.baidu.com"));
            urls.add(new URL("http://www.google.com"));
            urls.add(new URL("http://www.google.com/dasfad"));
            urls.add(new URL("http://www.jgoodies.com"));        CheckURLWorker w1 = new CheckURLWorker("w1",urls);
            CheckURLWorker w2 = new CheckURLWorker("w2",urls);
            new Thread(w1).start();
            new Thread(w2).start();
        }    private static class CheckURLWorker implements Runnable {
            private BlockingQueue<URL> queue;
            private String name;
            public CheckURLWorker(String name,BlockingQueue<URL> q){
                this.name = name;
                this.queue = q;
            }        @Override public void run() {
                for (URL url = queue.poll(); url != null; url = queue.poll()) {
                    try{
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(3000);
                        connection.setRequestMethod("GET");
                        connection.connect();
                        int code = connection.getResponseCode();
                        connection.disconnect();
                        System.out.printf("[%s]%s:%d%n",name,url.toString(),code);
                    } catch (SocketTimeoutException e) {
                        System.out.printf("[%s]%s:%d%n",name,url.toString(),-1);
                    } catch (IOException e) {
                        System.err.println(e);
                    }
                }
            }
        }
    }
      

  12.   

    http://topic.csdn.net/u/20111121/10/b6c436d1-f44a-4467-8174-b9d519444f85.html
    这个帖子的分要不要,也给你吧