无法理解同步

时间:2018-04-21 17:41:43

标签: java multithreading synchronization

嘿我试图以同步的方式制作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);
    }
}

1 个答案:

答案 0 :(得分:0)

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

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

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

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

相关问题