gpt4 book ai didi

java - 管理线程同步中的静态关键字 - Java

转载 作者:行者123 更新时间:2023-11-30 02:01:05 26 4
gpt4 key购买 nike

我对下面发布的代码有疑问。为什么我需要在 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 1
Current Sum for Thread 2 equals 3
Current Sum for Thread 2 equals 6
Current Sum for Thread 2 equals 10
Current Sum for Thread 2 equals 15
Current Sum for Thread 1 equals 1
Final Sum for Thread 2 equals 15
Thread 2 has been finished.
Current Sum for Thread 1 equals 3
Current Sum for Thread 1 equals 6
Current Sum for Thread 1 equals 10
Current Sum for Thread 1 equals 15
Final Sum for Thread 1 equals 15
Thread 1 has been finished.

结果为 SumArray sa = new SumArray();

Thread 2 is starting.
Thread 1 is starting.
Current Sum for Thread 2 equals 1
Current Sum for Thread 1 equals 1
Current Sum for Thread 1 equals 3
Current Sum for Thread 2 equals 3
Current Sum for Thread 2 equals 6
Current Sum for Thread 1 equals 6
Current Sum for Thread 1 equals 10
Current Sum for Thread 2 equals 10
Current Sum for Thread 2 equals 15
Current Sum for Thread 1 equals 15
Final Sum for Thread 2 equals 15
Thread 2 has been finished.
Final Sum for Thread 1 equals 15
Thread 1 has been finished.

最佳答案

因为在线程内部您创建了一个新对象,并且它有自己的 sumArray 方法。当它是静态时,整个 jvm 中只有一个 sumArray 函数属于类,而不属于对象

关于java - 管理线程同步中的静态关键字 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52801811/

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