gpt4 book ai didi

Java : one lock per method per object

转载 作者:行者123 更新时间:2023-12-02 04:01:58 25 4
gpt4 key购买 nike

我正在构建一个网络爬虫,它有两个主要功能,它们都作为线程执行:- getter (抓取网站并将文件中的单独链接存储到数据库中)。- 下载器(根据 fetcher 返回的 url 下载文件)。

我有一个对象WebSite,其中包含我想了解的有关网站的所有内容。现在我想操作我的数据库,将链接的状态从等待更改为正在获取,然后更改为已获取。文件从等待下载再到已下载也是如此。

为了防止 Fetcher 获取另一个 fetcher 选择的链接,我在我的 WebSite 对象中完成了此功能:

public synchronized String[] getNextLink(){
//Return the next link from database that has visited set to 0 then change it to -1 to say that it's in-use.
}

我也用这个函数为我的下载器做了同样的事情:

public synchronized String getNextFile(){
//Return the next file from database that has downloaded set to 0 then change it to -1 to say that it's downloading
}

这两种方法都在我的 WebSite 对象内,因为如果两个 Fetcher 正在使用不同的网站,他们无法选择我的数据库中的同一行(下载器也是如此)。但这两个函数可以同时调用,因为 Fetchers 永远不会选择文件,而 Downloaders 永远不会选择链接 .

现在同步正在使用单个锁(每个对象),因此我的两个方法不能同时调用。是否还有另一个关键字可以使用每个对象每个方法一个锁?或者我需要编码吗?

最佳答案

您可以使用两个独立的锁对象(以及任何 对象可以在方法中用作 Java 中的锁对象。每个锁对象将独立于其他对象:

private final Object fetcherMutex = new Object();
private final Object downloaderMutex = new Object();

public String[] getNextLink(){
synchronized (fetcherMutex) { /* ... */ }
}

public String[] getNextFile(){
synchronized (downloaderMutex) { /* ... */ }
}

关于Java : one lock per method per object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34790209/

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