这是 Herbert Schildt 的 Java Fundamentals 中演示同步的程序。方法sumArray(int[])
是synchronized
,这是程序正常工作的要求。但是,当我删除synchronized
关键字时,出乎意料的是,程序显示几乎相同的输出,并且仍然给出了正确的结果。这是程序。
class SumArray {
private int sum;
int sumArray(int[] nums) {
sum = 0; // Reset sum.
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
System.out.println("Running total for " + Thread.currentThread().getName() + " is " + sum);
}
return sum;
}
}
class SumThread implements Runnable {
static SumArray sa = new SumArray();
Thread thrd;
int[] a;
int answer;
public SumThread(String name, int[] nums) {
thrd = new Thread(this, name);
a = nums;
thrd.start();
}
@Override public void run() {
System.out.println(thrd.getName() + " starting.");
answer = sa.sumArray(a);
System.out.println("Sum for " + thrd.getName() + " is " + answer);
System.out.println(thrd.getName() + " terminating.");
}
}
public class SyncExample {
public static void main(String[] args) {
int[] a = new int[] {1, 2, 3, 4, 5, 6};
SumThread mt1 = new SumThread("Thread #1", a);
SumThread mt2 = new SumThread("Thread #2", a);
try {
mt1.thrd.join();
mt2.thrd.join();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
输出。
Thread #1 starting.
Running total for Thread #1 is 1
Running total for Thread #1 is 3
Running total for Thread #1 is 6
Running total for Thread #1 is 10
Running total for Thread #1 is 15
Running total for Thread #1 is 21
Sum for Thread #1 is 21
Thread #1 terminating.
Thread #2 starting.
Running total for Thread #2 is 1
Running total for Thread #2 is 3
Running total for Thread #2 is 6
Running total for Thread #2 is 10
Running total for Thread #2 is 15
Running total for Thread #2 is 21
Sum for Thread #2 is 21
Thread #2 terminating.
我的电脑有问题吗,或者线程应该这么奇怪?