gpt4 book ai didi

java - 在线程中运行的信号量任务

转载 作者:行者123 更新时间:2023-12-01 21:15:13 25 4
gpt4 key购买 nike

我有以下 Java 类(class)。第一个任务是修改类以获得 ABCABCABCABC 序列,使用线程,这非常简单。我只是通过将 a.acquire b.realse 放入 A 类中、将 b.acquire c.release 放入 C 类中以及 c.acquire 和 a.relase 来完成此操作。

现在,我必须修改类才能获取ABBCABBC 序列,但我正在为此苦苦挣扎。有人知道如何处理吗?

类代码:

import java.util.concurrent.Semaphore;

public class SemaphoresABC {

private static final int COUNT = 10; //Number of letters displayed by threads
private static final int DELAY = 5; //delay, in milliseconds, used to put a thread to sleep

private static final Semaphore a = new Semaphore(1, true);
private static final Semaphore b = new Semaphore(0, true);
private static final Semaphore c = new Semaphore(0, true);

public static void main(String[] args) {
new A().start(); //runs a thread defined below
new B().start();
new C().start();

}

private static final class A extends Thread { //thread definition

@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
for (int i = 0; i < COUNT; i++) {
//use semaphores here

System.out.print("A ");
//use semaphores here

Thread.sleep(DELAY);
}
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
System.out.println("\nThread A: I'm done...");
}
}

private static final class B extends Thread {

@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
for (int i = 0; i < COUNT; i++) {
//use semaphores here

System.out.print("B ");
//use semaphores here

Thread.sleep(DELAY);
}
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
System.out.println("\nThread B: I'm done...");
}
}

private static final class C extends Thread {

@Override
@SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
for (int i = 0; i < COUNT; i++) {
//use semaphores here

System.out.print("C ");
//use semaphores here

Thread.sleep(DELAY);
}
} catch (InterruptedException ex) {
System.out.println("Ooops...");
Thread.currentThread().interrupt();
throw new RuntimeException(ex);
}
System.out.println("\nThread C: I'm done...");
}
}
}

另外,一些解释为什么解决方案应该像你的那样,会派上用场。预先感谢您。

最佳答案

B 字母的循环应修改如下:

for (int i = 0; i < COUNT * 2; i++) {

b.acquire();

System.out.print("B ");

if (i % 2 == 1) {
c.release();
} else {
b.release();
}

Thread.sleep(DELAY);
}

这里:

  • COUNT 乘以 2,因为循环必须运行两倍的次数,因为 B 字母被打印两次。
  • i % 2 条件允许释放信号量 C,即继续每秒迭代。

关于java - 在线程中运行的信号量任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880530/

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