gpt4 book ai didi

Java 和模拟进程调度程序

转载 作者:搜寻专家 更新时间:2023-11-01 03:01:05 25 4
gpt4 key购买 nike

我非常感谢所有提供的帮助,但我现在正在努力完成任务的最后一部分,即使递增和递减交替发生。我编辑了整个主类和类 incrementer,它包含一个调用 Main.increment 给定次数的 for 循环(有一个类 decrementer,其样式与 icrementer 相同所以我没有包括它)。你能帮助我如何实现这一目标吗?如果我理解正确,我希望使 sharedValue 的值在 1 和 0 之间切换。

public class Main extends Thread {

private static int sharedValue = 0;
private static Semaphore semaphore = new Semaphore(1);

public static void increment() {
semaphore.down();
sharedValue++;
semaphore.up();
}

public static void decrement() {
semaphore.down();
sharedValue--;
semaphore.up();
}

static int numberOfCycles = 20000;

public static void main(String[] args) throws InterruptedException {

incrementer inc = new incrementer(numberOfCycles);
inc.start();
inc.join();

decrementer dec = new decrementer(numberOfCycles);
dec.start();
dec.join();

System.out.println(sharedValue);

}}

信号量类

private int count;
// Constructor
public Semaphore(int n) {
count = n;
}

// Only the standard up and down operators are allowed.
public synchronized void down() {

while (count == 0) {

try {
wait(); // Blocking call.
} catch (InterruptedException exception) {
}
}
count--;
}

public synchronized void up() {
count++;
notify();
}
}

增量类

公共(public)类增量器扩展线程{

私有(private) int numberOfIncrements;

public incrementer(int numOfIncrements){
numberOfIncrements = numOfIncrements;
}
public void run(){
for(int i = 0; i <= numberOfIncrements; i++){
Main.increment();
}
}

再次感谢。

最佳答案

我认为他的意思是受信号量保护。所以,你会使用类似的东西:

class ProtectedCount {
private static int sharedValue = 0;
private static Semaphore semaphore = new Semaphore(1);
public void increment() {
semaphore.down(); // wait till the semaphore is available
sharedValue++;
semaphore.up(); // tell everyone that the semaphore is available
}
// same thing for decrement()
}

这演示了使用信号量提供互斥。此用例类似于互斥量。参见 semaphore vs. mutex on Wikipedia .

关于Java 和模拟进程调度程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34229472/

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