有一道题目要求我在主线程中在创建两个线程,其中一个负责输入数字,另各一个求和并输出,而且两个线程的操作必须同步
我的程序是这样的,但始终不能运行成功,请个为高手帮帮我
import java.util.*;public class InputThread implements Runnable
{
private static int m = 0;
private static int n = 0; public void run()
{
for (int i = 0; i < 3; i++)
{
if (Thread.currentThread().getName().equals("t1"))
{
InputNumber();
}
else
{
calculateResult();
}
}
} public synchronized void InputNumber()
{ Scanner in = new Scanner(System.in);
m = in.nextInt();
n = in.nextInt(); } public synchronized void calculateResult()
{ System.out.println("The sum of the two Integer is " + (m + n)); } public static void main(String[] args)
{
new Thread(new InputThread(), "t1").start();
new Thread(new InputThread(), "t2").start();
}
}
我的程序是这样的,但始终不能运行成功,请个为高手帮帮我
import java.util.*;public class InputThread implements Runnable
{
private static int m = 0;
private static int n = 0; public void run()
{
for (int i = 0; i < 3; i++)
{
if (Thread.currentThread().getName().equals("t1"))
{
InputNumber();
}
else
{
calculateResult();
}
}
} public synchronized void InputNumber()
{ Scanner in = new Scanner(System.in);
m = in.nextInt();
n = in.nextInt(); } public synchronized void calculateResult()
{ System.out.println("The sum of the two Integer is " + (m + n)); } public static void main(String[] args)
{
new Thread(new InputThread(), "t1").start();
new Thread(new InputThread(), "t2").start();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货