程序清单

news/2024/7/19 9:57:13 标签: java, 爬虫

 

 

程序清单 5-8 桌面搜索应用程序中的生产者任务和消费者任务(和书上有所不同,有些许改动)


 

1、生产者

package com.everjiankang.miaosha;

import java.io.File;
import java.io.FileFilter;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * 文件爬虫程序
 * @author guchunchao
 *
 */
public class FileCrawer implements Runnable {

    private final BlockingQueue<File> fileQueue;
    private final FileFilter fileFilter;
    private final File root;
    private final Set<String> alreadyExistFileSet = new ConcurrentSkipListSet<>();
        
    public FileCrawer(BlockingQueue<File> fileQueue, FileFilter fileFilter, File root) {
        super();
        this.fileQueue = fileQueue;
        this.fileFilter = fileFilter;
        this.root = root;
    }


    @Override
    public void run() {
        try {
            this.crawl(root);
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }
    
    
    private void crawl(File root) throws InterruptedException {
        if(root != null) {
            File[] entries = root.listFiles(fileFilter);
            if(entries != null) {
                for(File file : entries) {
                    if(file.isDirectory()) 
                        crawl(file);
                    else if(!alreadyIndexed(file)) {
                        System.out.println("生产者放入队列:" + file.getPath() + file.getName());
                        fileQueue.put(file);
                        alreadyExistFileSet.add(file.getPath()+file.getName());
                    }
                }
            } 
        }
    }
    
    private boolean alreadyIndexed(File file) {
        return alreadyExistFileSet.contains(file.getPath()+file.getName());
//        return fileQueue.contains(file);
    }

}

 

2、消费者

package com.everjiankang.miaosha;

import java.io.File;
import java.util.concurrent.BlockingQueue;

/**
 * 消费者,建立文件索引
 * @author guchunchao
 *
 */
public class Indexer implements Runnable {
    
    private final BlockingQueue<File> queue;
    
    public Indexer(BlockingQueue<File> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while(true) {
                indexFile(queue.take());
            }
        } catch(InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }

    private void indexFile(File file) {
        System.out.println("消费:" + file.getPath()+file.getName());
    }

}

 

3调用

package com.everjiankang.miaosha;

import java.io.File;
import java.io.FileFilter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class XiaoFeiQueue {
    private final static int BOUND = 10;
    private final static int N_CONSUMMERS = 10;

    public static void main(String[] args) {
        File file = new File("/Users/guchunchao/Desktop/深入理解java虚拟机视频1-6");
        File[] files = new File[10];
        files[0] = file;
        startIndexing(files);

    }
    
    public static void startIndexing(File[] files) {
        BlockingQueue<File> queue = new LinkedBlockingDeque<File>(BOUND);
        FileFilter filter = new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return true;
            }
        };
        
        //n个线程爬取文件
        for(File file : files) {
            new Thread(new FileCrawer(queue, filter, file)).start();
        }
        
        //10个线程消费
        for(int i = 0; i < N_CONSUMMERS; i++) {
            new Thread(new Indexer(queue)).start();
        }
    }

}

 


 

 

 

程序清单 5-11 在计测试中使用CountDownLatch来启动和停止线程


 

 

public static void say(int nThread, Runnable run) throws InterruptedException {
        CountDownLatch startDoor =new CountDownLatch(1);
        CountDownLatch endDoor = new CountDownLatch(nThread);
        for(int i = 0; i < nThread; i++) {
            new Thread() {
                @Override
                public void run() {
                    try {
                        startDoor.await();
                        try {
                            run.run();
                        }finally {
                            endDoor.countDown();
                        }
                    } catch (InterruptedException e) {
                    }
                }
            }.start();
        }
        
        long startTime = System.nanoTime();
        startDoor.countDown();
        endDoor.await();
        long endTime = System.nanoTime();
        System.out.println(nThread + "个线程总共花费了" + (endTime - startTime) + " ns");
}

 

转载于:https://www.cnblogs.com/guchunchao/p/10658372.html


http://www.niftyadmin.cn/n/1660095.html

相关文章

JavaScript基础-4

4 流程控制 4.1 顺序结构 顺序结构是程序中最简单、最基本的流程控制&#xff0c;他没有特定的语法结构&#xff0c;程序会按照代码的先后顺序执行&#xff0c;程序中大多数的代码都是这样执行的&#xff1b; 4.2 分支结构 if 分支结构注意&#xff1a;if 适用于范围判断&#…

探索java异常处理

通过本章的学习可以达到一下目标&#xff1a; item 了解异常的产生原理 掌握异常处理语句的基本格式 掌握throw和throws关键字的作用 可以自定义异常 了解Exception与RuntimeException的区别 了解断言的作用 认识异常&#xff1a; 关于被除数不能为0的说明&#xff1a; 被除数为…

posgreSQL安装失败解决方案

选择适合自己电脑版本的postgreSQL进行安装&#xff0c;显示安装失败&#xff0c;错误信息&#xff1a;problem running post-install step.installation may not complete correctly the database cluster innitialisation failed 解决方案&#xff1a; 1、dos 窗口 (cmd 执行…

Qt5 GUI 开发的应用易受远程代码执行漏洞的影响

2019独角兽企业重金招聘Python工程师标准>>> 外媒 Bleepingcomputer 报导称使用 Qt5 GUI 框架开发的应用程序容易面临远程代码执行漏洞。攻击者通过一个鲜为人知的命令行参数配置自定义协议处理程序&#xff0c;就可利用这个漏洞。 许多开发者并不知道当使用 Qt5 框…

基于Redis和Lua的分布式限流

Java单机限流可以使用AtomicInteger&#xff0c;RateLimiter或Semaphore来实现&#xff0c;但是上述方案都不支持集群限流。集群限流的应用场景有两个&#xff0c;一个是网关&#xff0c;常用的方案有Nginx限流和Spring Cloud Gateway&#xff0c;另一个场景是与外部或者下游服…

盒子模型基本介绍及知识点

盒子模型 盒子模型&#xff1a; 就是把HTML页面中的布局元素看作是一个矩形的盒子&#xff0c;也就是一个盛装内容的容器。 盒子模型有元素的内容、边框&#xff08;border&#xff09;、内边距&#xff08;padding&#xff09;、和外边距&#xff08; margin&#xff09;组 …

《密码与安全新技术专题》第三周作业

学号 2018-2019-2 《密码与安全新技术专题》第三周作业 课程&#xff1a;《密码与安全新技术专题》 班级&#xff1a; 92班 姓名&#xff1a;张宇翔 学号&#xff1a;20189211 上课教师&#xff1a;谢四江 上课日期&#xff1a;2019年3月2日 必修/选修&#xff1a; 选修 1.本次…

VUE 监控 VUEX 中的状态

背景&#xff1a;在一个项目中&#xff0c;需要获取 侧边栏展开/收缩 的状态&#xff0c;&#xff08;侧边栏展开/收缩的状态已经存到vuex中&#xff09;来resize图表(v-charts)。方法&#xff1a;computed: {getAsideCollapse() { //获取并返回侧边栏状态return this.$…