gpt4 book ai didi

java - 对信号量类有点困惑

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:49:53 24 4
gpt4 key购买 nike

我对 java.util.concurrent 包中的“Semaphore”类有点困惑。这是我的代码片段:

import java.util.concurrent.Semaphore;

public class TestSemaphore {
public static void main(String[] args){
Semaphore limit = new Semaphore(2);
SemaphoreAA s = new SemaphoreAA(limit);
AAThread a = new AAThread(s);
Thread[] sThread = new Thread[100];
for(int i = 0; i<100; i++){
sThread[i] = new Thread(a,"[sThread"+i+"]");
sThread[i].start();

}
}
}

class SemaphoreAA{
private static int counter;
private Semaphore limit;

public SemaphoreAA(Semaphore limit){
this.limit = limit;
}

public void increment() throws InterruptedException{
System.out.printf("%-15s%-25s%5d%n",Thread.currentThread().getName()," : Before Increment. Current counter: ",counter);
limit.acquire();
System.out.printf("%-15s%-25s%n",Thread.currentThread().getName()," : Get the resource. Start to increment.");
counter++;
System.out.printf("%-20s%-40s%5d%n",Thread.currentThread().getName()," : Increment is done. Current counter: ",counter );
limit.release();
}
}

class AAThread implements Runnable{
private SemaphoreAA s;

public AAThread(SemaphoreAA s){
this.s = s;

}

public void run() {
try {
s.increment();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

我知道它可以用来控制对资源的访问。如果我将限制设置为 1,就像这样“Semaphore limit = new Semaphore(1);”,它看起来就像一把锁。它被证明了。如果我将限制设置为两个,我预计在给定时间内有两个线程访问 increment() 方法,这可能会导致数据竞争。输出可能是这样的:

  • [sThread3] : Before Increment. Current counter: 2
  • [sThread4] : Before Increment. Current counter: 2
  • [sThread3] : Get the resource. Start to increment.
  • [sThread4] : Get the resource. Start to increment.
  • [sThread3] : Increment is done. Current counter: 3
  • [sThread4] : Increment is done. Current counter: 3

然而,虽然我尝试了几次,但并没有出现预期的结果。所以我想知道我是否误解了它。谢谢。

最佳答案

你没看错。

However, though I had tried several times, the result expected didn't occur.

仅仅因为它会出现并不意味着它会出现。这是大多数并发错误的问题:它们有时出现,有时不出现。

如果您想增加出错的可能性,您可以增加 Thread 的数量或在两个不同的循环中创建/启动它们。

关于java - 对信号量类有点困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20662447/

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