-1
我想有3種方法在同一時間,所以我可以運行例如連續添加3次,或者減去並隨時檢查。我該怎麼做呢?到目前爲止,我的輸出僅僅是三種方法。線程在Java中,其中3種名爲方法同時運行
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) {
add();
remove();
check();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
t1.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);
}
}
你只需要一個線程或期望越來越高,你肯定要靜態方法的? – SMA 2014-11-22 14:35:26
「同時運行」並不意味着你認爲這意味着什麼...你的實際目標是什麼? – specializt 2014-11-22 16:20:36