【发布时间】:2021-05-25 18:09:30
【问题描述】:
我有三个线程,我需要将三个线程同步在一起, 我从用户那里获取 n 直到需要计数器并增加 counterOne 直到 n 值 (通过使用 ThreadOne) 并且如果 counterOne 是 25 的倍数,我需要增加值 counterTwo 乘以 2**(通过使用 hreadTwo)** 并且当 counterTwo 是 4 的倍数时,我 需要将 counterThree 增加 1 (通过使用 ThreadThree) 并且需要打印值 n = counterOne 值之后的 counterOne、counterTwo 和 counterThree。
我已经实现了这个,这是代码,但是 counterTwo 和 counterOne 的值没有增加。 我做错了什么?
测试用例
输入:30
输出 : counterOne: 30, counterTwo: 0 counterThree:0
CounterOne 将一一增加,当遇到 25 倍数时 counterTwo 应增加二,当添加 4 倍数时 counterThree 应增加一。
但是当在 counterOne 中添加 25 时,它应该将 counterTwo 增加 2,但它没有增加 counterOne 到 30 4 ,8,12,16,20,24,28 这些都是 4 的倍数,所以counterThree 应该是 7,但它也是 0。
输出应该是:counterOne: 30, counterTwo: 1 counterThree:7
代码如下:
计数器类
public class Counter {
int counterOne;
int counterTwo;
int counterThree;
int flag = 0;
}
主类
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Counter count = new Counter();
ThreadOne objOne = new ThreadOne(count, n);
Thread one = new Thread(objOne);
ThreadTwo objTwo = new ThreadTwo(count);
Thread two = new Thread(objTwo);
ThreadThree objThree = new ThreadThree(count);
Thread three = new Thread(objThree);
try {
one.start();
two.start();
three.start();
} catch (Exception e) {
e.printStackTrace();
}
in.close();
}
}
ThreadOne 类
class ThreadOne implements Runnable {
Counter count;
int n;
public ThreadOne(Counter count, int n) {
this.count = count;
this.n = n;
}
@Override
public synchronized void run() {
while (count.counterOne != n) {
count.counterOne += 1;
}
if (count.counterOne == n) {
count.flag = 1;
System.out.print(count.counterOne + " " + count.counterTwo + " " + count.counterThree);
}
}
}
ThreadTwo 类
class ThreadTwo implements Runnable {
Counter count;
public ThreadTwo(Counter count) {
this.count = count;
}
@Override
public synchronized void run() {
while (count.flag != 1) {
if (count.counterOne % 25 == 0) {
count.counterTwo += 2;
}
}
}
}
ThreadThree 类
class ThreadThree implements Runnable {
Counter count;
public ThreadThree(Counter count) {
this.count = count;
}
@Override
public synchronized void run() {
while (count.flag != 1) {
if (count.counterTwo % 4 == 0) {
count.counterThree += 1;
}
}
}
}
【问题讨论】:
-
您可能想查看可见性保证、
volatile和原子引用。 -
我不清楚这些解释。我认为您需要向我们展示minimal reproducible example 以向我们展示实际问题,如果不是,请在文本中添加进一步的解释。
-
@markspace 添加示例
标签: java multithreading synchronization