gpt4 book ai didi

java - 多线程,以便不断从集合 int 中减去或添加数字

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

我想让 3 个线程同时执行,一个用于添加总计,一个用于从总计中减去,一个用于检查总计。减去或添加的金额由用户通过控制台输入。

到目前为止我已经:

import java.util.Scanner;

public class Calc implements Runnable {

public int add;
public int remove;
public static int Total;

static Scanner s = new Scanner(System.in);

public static int add(int a){
System.out.println("How much was added? \n");
a = s.nextInt();
Total = Total + a;
return Total;
}


public int remove(int b){
System.out.println("How much was removed? \n");
b = s.nextInt();
return Total = Total - b;
}

public void check(){
System.out.println("Would you like to know how much is left? \n");
if(s.nextLine().equals("Yes"))
System.out.println(Total);

}


@Override
public void run() {
// TODO Auto-generated method stub

}

}


public class Calculate{
public static void main(String[] args){

Thread t1 = new Thread(new Calc("add"));
Thread t2 = new Thread(new Calc("remove"));
Thread t3 = new Thread(new Calc("check"));

t1.start();
t2.start();
t3.start();
}
}

有人能指出我正确的方向吗?

最佳答案

我不明白这有什么用处,但对于您的特殊需求,您“可能”可以使用类似的东西:

import java.util.Scanner;

public class Calc {

public static void main(String[] args) {

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
while (true) { // change condition to whatever
add();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
while (true) { // change condition to whatever
remove();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
Thread t3 = new Thread(new Runnable() {

@Override
public void run() {
while (true) { // change condition to whatever
check();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});

t1.start();
t2.start();
t3.start();

}

static int total = 0;

static Scanner s = new Scanner(System.in);

static synchronized int add() {
System.out.println("How much was added?");
int a = s.nextInt();
total = total + a;
return total;
}

static synchronized int remove() {
System.out.println("How much was removed?");
int b = s.nextInt();
return total = total - b;
}

static synchronized void check() {
System.out.println("Would you like to know how much is left?");
String str = s.next();
if (str.equals("Yes"))
System.out.println(total);

}

}

请注意,您不需要使用线程来完成您想要做的事情。

关于java - 多线程,以便不断从集合 int 中减去或添加数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27024415/

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