Java 多线程处理,使数字不断地从一组整数中减去或加上
我希望有3个线程同时执行,一个用于相加,一个用于从总数中减去,一个用于检查总数。减去或增加的金额由用户通过控制台输入 到目前为止,我已经:Java 多线程处理,使数字不断地从一组整数中减去或加上,java,Java,我希望有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
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);
}
}
请注意,您不需要使用线程来完成您要做的事情