我有一个关于下面发布的代码的问题。为什么我需要在 SumArray 对象的声明前面加上“static”这个词才能使这段代码正常运行?为什么不保证(由它自己)一次为一个线程调用同步方法?事实上,如果我删除“静态”一词,那么 SumArray 方法将被 2 个线程调用可互换。尽管如此,两个线程的总和将是正确的。class SumArray { private int sum; synchronized int sumArray(int numbers[]) { sum = 0; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; System.out.println("Current Sum for " + Thread.currentThread().getName() + " equals " + sum); try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("Main Thread has been stopped"); } } return sum; }}class MyThread implements Runnable { Thread t; int a[]; int ans; static SumArray sa = new SumArray(); MyThread(String name, int numbers[]) { t = new Thread(this, name); t.start(); a = numbers; } public void run() { System.out.println(t.getName() + " is starting."); ans = sa.sumArray(a); System.out.println("Final Sum for " + t.getName() + " equals " + ans); System.out.println(t.getName() + " has been finished."); }}public class Main { public static void main(String[] args) { int a[] = { 1, 2, 3, 4, 5 }; new MyThread("Thread 1", a); new MyThread("Thread 2", a); }}代码的示例结果 static SumArray sa = new SumArray();Thread 2 is starting.Thread 1 is starting.Current Sum for Thread 2 equals 1Current Sum for Thread 2 equals 3Current Sum for Thread 2 equals 6Current Sum for Thread 2 equals 10Current Sum for Thread 2 equals 15Current Sum for Thread 1 equals 1Final Sum for Thread 2 equals 15Thread 2 has been finished.Current Sum for Thread 1 equals 3Current Sum for Thread 1 equals 6Current Sum for Thread 1 equals 10Current Sum for Thread 1 equals 15Final Sum for Thread 1 equals 15Thread 1 has been finished.结果与 SumArray sa = new SumArray();
1 回答
眼眸繁星
TA贡献1873条经验 获得超9个赞
因为在线程内部您创建了一个新对象并且它有自己的 sumArray 方法。当它是静态时,整个 jvm 中只有一个 sumArray 函数属于类,而不是对象
添加回答
举报
0/150
提交
取消