java - 共享资源先到先得政策

标签 java multithreading concurrency scheduling

试题:

A resource is shared between N threads such that access is on a first-come-first-served basis. Explain how you would implement a policy of first-come-first-served.

我的回答是(注意:类(class)是基于 Java 的):

Use a semaphore (binary) to control access to the shared resource. Then create a feeder class/thread to access the semaphore. The feeder thread uses a FIFO queue to implement first-come-first-served. When the semaphore is free it allows the thread a the head of the queue to access the shared resource.

我刚刚在纸上记下了上述方法,它似乎有效。

该问题在 20 分问题中值(value) 8 分,因此我怀疑使用 new ReentrantLock(true) 是否足以获得满分。

大家怎么看?

最佳答案

您的回答确实没有解决问题。这不仅与锁定有关,还与排队等待资源的线程有关。

  • 如何对等待资源的线程进行排队?
  • 如果有线程在等待资源,您如何唤醒它们以便它们按顺序使用资源。
  • 如果有线程在等待资源,您如何确保它们按顺序运行并避免围绕新线程抢占它的竞争条件。

一个可能的解决方案类似于下面的代码:

  lockResource(resource);
  try {
     ... consume the resource
  } finally {
     unlockResource(resource);
  }

lockResource 会做类似的事情:

  1. 获取资源锁。
  2. 检索与包含 long accessNumlong runningNum 的资源关联的锁对象。
  3. 增加 accessNum 值并存储线程的结果。
  4. 检查 long runningNum 值以查看是否 == 到我的 accessNum
  5. 如果是==我的,解锁资源并继续运行。
  6. 如果队列中的人数多于我,请在资源上wait()

unlockResource(...) 被调用时,线程应该:

  1. 锁定资源。
  2. 设置运行++
  3. 调用notifyAll()
  4. 解锁资源

如果线程正在等待并被唤醒:

  1. 检查是否 accessNum == runningNum
  2. 如果为真则解锁资源并继续运行
  3. 如果没有则返回wait()

关于java - 共享资源先到先得政策,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11605555/

相关文章:

java - 从技术上讲,您可以在 main 方法中调用 string[] 吗?

c++ - 另一个线程的调试实例改变了我的数据

c++ - 为什么在删除原子引用计数智能指针中的数据之前需要获取屏障?

java - 交换器似乎没有交换()

java - 重命名包后Eclipse “Error: Could not find or load main class”

java - 我的微调器和 ListView 中出现重复数据

java - 在没有可用的entrySet()的情况下迭代NavigableSet

multithreading - 带网络代码的OpenGL程序示例?

php - Guzzle 中的 "concurrency"到底是什么?

java - Java 中有多少种内存屏障?