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

我有一个关于下面发布的代码的问题。为什么我需要在 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();

桃花长相依
浏览 120回答 1
1回答

眼眸繁星

因为在线程内部您创建了一个新对象并且它有自己的 sumArray 方法。当它是静态时,整个 jvm 中只有一个 sumArray 函数属于类,而不是对象
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java