【问题标题】:how to get the acquired index from Semaphore如何从 Semaphore 获取获取的索引
【发布时间】:2019-10-22 09:05:46
【问题描述】:

我有一个大小为 4 的 int 数组,一次只有一个线程可以访问一个数组单元。 我考虑过使用信号量,但我不知道如何或是否有办法获取获取的索引 我构建了一个代码示例来解释黄油:

public class Temp {

    private ExecutorService executeService;
    private Semaphore semaphore;
    private int[] syncArray; // only one thread can access an array cell at the same time

    public Temp() {
        syncArray = new int[]{1,2,3,4};
        executeService = Executors.newFixedThreadPool(10);
        semaphore = new Semaphore(syncArray.length, true);

        for(int i = 0;i < 100; i++) {
            executeService.submit(new Runnable() {
                @Override
                public void run() {
                    semaphore.acquire();

                    // here I want to access one of the array cell
                    // dose not matter witch one as long as no other thread is currently use it
                    int syncArrayIndex = semaphore.getAcquiredIndex(); // is something like this possible?
                    syncArray[syncArrayIndex] += ...;

                    semaphore.release();
                }
            });
        }

    }
}

编辑: 这是一段看起来更接近我真正问题的代码:

public class Temp {

    private ExecutorService executeService;
    private Semaphore semaphore;
    private static ChromeDriver driver;

    public Temp() {
        executeService = Executors.newFixedThreadPool(10);
    }

    public Future<WikiPage> getWikiPage(String url) {
        executeService.submit(new PageRequest(url) {

        });
    }

    private static class PageRequest implements Callable<WikiPage> {
        String url;
        public PageRequest(String url) {
            this.url = url;
        }
        @Override
        public WikiPage call() throws Exception {
            String html = "";
            synchronized (driver) {
                html = ...// get the wiki page, this part takes a log time
            };
            WikiPage ret =  ...// parse the data to the WikiPage class
                            // this part takes less time but depend on the sync block above

            return ret;
        }
    }
}

@Kayaman 我不确定我是否理解您的评论,问题是我返回了一个未来。您对如何改进我的代码以更快地运行有什么建议吗?

【问题讨论】:

  • "permits" 无法识别。您不能使用单个 Semaphore 单独访问 4 个不同的对象。

标签: java multithreading thread-safety semaphore


【解决方案1】:

不,信号量在这里没有用。它只知道它有多少许可,信号量中没有“索引”。

您可以改用AtomicIntegerArray,尽管如果您解释了您的根本问题,可能会有更合适的类可供使用。

【讨论】:

  • 我在 selenium 中使用 chromeDriver 来获取 Wikipedia 页面,从 chromeDriver 获取我需要的部分比我对数据进行的处理花费的时间要长得多。所以我想同时在 4 个不同的维基百科页面上使用 4 个 chromeDrivers
  • @roni 那么你可能想做一些事情,比如将抓取的数据放入队列中,处理器将从队列中取出、处理和存储。与Semaphore 共享int[] 绝对是错误的方式。
  • 我不确定我是否能 100% 理解你的答案,所以我添加了一个更接近我的真实代码的代码,我希望你能就你的想法给我一个意见。跨度>
  • @roni 好吧,您正在driver 上同步,使代码成为单线程。这是你的主要问题。如果您想要任何改进,则每个线程都需要一个驱动程序。
  • 我知道,但驱动线程不是一个选项,这就是为什么我想要所有线程的 4 个驱动程序。这可能吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-21
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-31
  • 1970-01-01
相关资源
最近更新 更多