【发布时间】:2018-04-21 17:41:43
【问题描述】:
嘿,我正在尝试以同步方式创建 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);
}
}
【问题讨论】:
-
请修正您的代码缩进。
-
"我想出了代码" - "我不确定这部分代码的作用" - 你的意思是“我复制了代码”,对吗?最好问问作者它是做什么的。另一个获取信息的好地方是official Oracle Lesson on Concurrency。但老实说,如果您是 Java 新手,请从 basics 开始。代码注释:类名应始终以大写字母开头。
-
@Turing85 我明白发生了什么,但我不明白为什么要传递对象 d 以及 di.count 是如何工作的?
-
这与同步无关。
di.count访问实例di的字段count(其类型为data,继承自item)。正如我之前所说:从基础开始。 -
这不是我要问的,我想了解为什么需要
d=syn.increment(d),
标签: java multithreading synchronization