无法理解同步

问题描述 投票:0回答:1

嘿我试图以同步的方式制作10个线程,然后我想出了下面的代码,但是我无法理解它的一部分,如下所述。我仍然是java的新手,我尝试从Here查找同步线程,但我仍然无能为力。

class question3 {
    public static void main(String arg[]) throws Exception {
        for (int i = 0; i < 11; i++) {
            data di = new data();
            System.out.println(di.count);

        }
    }
}

class item {
    static int count = 0;
}

class data extends item implements Runnable {
    item d = this;
    Thread t;

    data() {
        t = new Thread(this);
        t.start();
    }

    public void run() {
        d = syn.increment(d);
    }
}

class syn {
    synchronized static item increment(item i) {
        i.count++;
        return (i);
    }

}

我不确定这部分代码是做什么的?

public void run() {
        d = syn.increment(d);
    }
}

class syn {
    synchronized static item increment(item i) {
        i.count++;
        return (i);
    }
}
java multithreading synchronization
1个回答
0
投票

在启动线程时使用run函数,这是在实现Runnable时需要覆盖的必需函数。调用Thread.start()时,将调用run函数。

class syn包含一个synchronized方法,它只是意味着每次只有一个线程可以访问它,从而使incerment函数线程安全。

对象d有一个静态变量count意味着item类(和data)的所有实例共享相同的count,所以所有线程都增加相同的变量

线d = syn.increment(d);基本上是count++但是以线程安全的方式

© www.soinside.com 2019 - 2024. All rights reserved.