gpt4 book ai didi

java - Java中带有监视器的生产者/消费者的多个实例

转载 作者:行者123 更新时间:2023-12-03 23:07:22 25 4
gpt4 key购买 nike

我正在构建一个网络爬虫来从网站下载文件。我有一个生产者(链接 getter )和一个消费者(下载器)。

它们都可以总结如下:

//Fetcher implements Runnable
public void run(){
while(String link = getLinkFromDatabase != null){
String htmlContent = HTTPrequest.getHTMLtoString(link);
ArrayList<String> links = HTTPrequest.getUrlsFromString(htmlContent); //Custom Parser/Extractor
ArrayList<String> files = HTTPrequest.getFilesFromString(htmlContent);//Custom Parser/Extractor
String SqlQueryAddLinks = "INSERT IGNORE DUPLICATE INTO [...]"; //Insert query for Links with unique key : sha256 of the url.
String SqlQUeryAddFiles = "INSERT IGNORE DUPLICATE INTO [...]"; //Insert query for Files with unique key : sha256 of the url.
Queries.sqlExec(SqlQueryAddLinks);
int RowAffected = Queries.sqlExec(SqlQueryAddFiles);
Queries.archiveLink(link);
Monitor.append(RowAffected);
}
}

//Downloader implements Runnable
public void run(){
while(String link = getFileFromeDatabase != null){
//You don't care of steps here I just download the file
if(fileDownloaded){
Queries.archiveFile(link);
Monitor.take();
}
}
}

现在我正在尝试同步两个线程以确保链接不会太旧。为此,我使用了 Monitor(如 William Stallings 撰写的操作系统:内部结构和设计原则中所述)

public class Monitor{
int N = 10;
int count;
Condition notfull, notempty;

public Monitor(){
count = 0;
}

public void append(int nbr) throws InterruptedException{
if(count >= N){
notfull.wait();
}
count+=nbr;
notempty.signal();
}

public void take() throws InterruptedException{
if(count == 0){
notempty.wait();
}
count--;
notfull.signal();
}

现在的问题是,我想通过监视器启动多个提取器和下载器同步。我是否需要创建一个新的 Monitors 对象并将 Monitor 添加到我的 Downloader 和 Fetcher 的类中,还是有更好的方法?这本书不是在谈论多个生产者/消费者,而是在 C++ 中使用函数 parbegin(producer, consumer);(我假设它是 C++)。

最佳答案

仅通过目测,这段代码由于多种原因无法编译,并且肯定会出现运行时故障。

a) 您尝试调用静态方法 take/append 但它们不是静态的。

b) 您尝试拥有 2 个 Condition 对象,但您没有可重入锁。

c) 在等待/通知之前你甚至没有锁定/解锁条件后面的可重入锁

d) 你使用 Condition.wait() 而不是 .await()。

e) 你正在使用 Condition.signal() 而不是 .signalAll()

关于java - Java中带有监视器的生产者/消费者的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34724366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com