zoukankan      html  css  js  c++  java
  • 爬虫中基本的多线程

    因为Java语言中不允许继承多个类,所以一个类一旦继承了 Thread类,就不能再继承其他
    类了。为了避免所有线程都必须是Thread的子类,需要独立运行的类也可以继承一个系统已经
    定义好的叫作Runnable的接口。Thread类有个构造方法public Thread(Runnable target)。当线程
    启动时,将执行target对象的run()方法。Java内部定义的Runnable接口很简单。

    public interface Runnable {
    public void run();
    }

    实现这个接口,然后把要同步执行的代码写在nm()方法中,测试类。

    public class Test implements Runnable {
    public void run() {
    System.out.println ("test") / //同步执行的代码
    }

    运行需要同步执行的代码。

    public class RunIt {
    public static void main(String[] args) {
    Test a = new Test();
    //a.run();错误的写法
    //Thread需要一个线程对象,然后它用其中的代码向系统申请CPU时间片
    Thread thread=new Thread(a);
    thread.start();
    }

    用不同的线程处理不同的目录页。

    public class DownloadSina implements Runnable {
        private static int i = 1;
    
        @Override
        public void run() {
            String url = null;
            for (;;) {
                synchronized ("") {
                    url = "http://roll.mil.news.sina.com.cn/col/zgjq/index" + i++
                            + ".shtml";
                }
    
                System.out.println(url);
                // 执行下载和处理目录页
            }
        
        }
    
        public static void main(String[] args) throws Exception {
            DownloadSina st = new DownloadSina();
            Thread tl = new Thread(st); // 启动3个下载线程
            Thread t2 = new Thread(st);
            Thread t3 = new Thread(st);
            tl.start();
            t2.start();
            t3.start();
        }
    
    }

    在Java中,为了爬虫稳定性,也可以用多线程来实现爬虫。一般情况下,爬虫程序需要能
    在后台长期稳定运行。下载网页时,经常会出现异常。有些异常无法捕获,导致爬虫程序退出。
    为了主程序稳定,可以把下载程序放在子线程执行,这样即使子线程因为异常退出了,但是主
    线程并不会退出。测试代码如下所示。

    public class Mythread extends Thread {
        public void run() {
            System.out.println("Throwing in " +"MyThread");
            throw new RuntimeException();
        }
    }
    public class ThreadTest{
        public static void main(String[] args) {
            Mythread t = new Mythread();
            t.start();
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
                System.out.println("Caught it");
            }
            System.out.println("Exiting main");
        }
    }
  • 相关阅读:
    安装 Ruby, Rails 运行环境
    saas 系统租户个性化域名&&租户绑定自己域名的解决方案
    caddy server 几个常用插件
    caddy server && caddyfile
    caddy server 默认https && http2的验证
    caddy server 了解
    redis 连接池的一些问题
    Hangfire 任务调度
    Spring Cloud feign 服务超时处理
    windows 2016 容器管理
  • 原文地址:https://www.cnblogs.com/Michael2397/p/7824844.html
Copyright © 2011-2022 走看看