我想同步
functionB
。我的意思是,当某些 Attribute
对象调用 functionA
时,总是同时运行对象的 functionB
之一。但是每个对象中的functionC
和functionD
可以在functionB
自己完成后完成。
我尝试在
functionB
中添加同步,但似乎不起作用。
这是
Attribute
课程:
public class Attribute {
private String name;
Attribute(String name) {
this.name = name;
}
public void functionA() {
synchronized (this) {
functionB();
}
functionC();
functionD();
}
private void functionB() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " " + i + " time functionB.");
}
}
private void functionC() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " " + i + " time functionC.");
}
}
private void functionD() {
for (int i = 0; i < 5; i++) {
System.out.println(name + " " + i + " time functionD.");
}
}
public static void main(String[] args) throws IOException {
ArrayList<Attribute> attributes = new ArrayList<>();
for (int i = 0; i < 5; i++) {
attributes.add(new Attribute("No." + i));
}
attributes.parallelStream().forEach(Attribute::functionA);
}
}
上述代码执行后,控制台显示:
No.3 0 time functionB.
No.4 0 time functionB.
No.2 0 time functionB.
No.2 1 time functionB.
No.2 2 time functionB.
No.1 0 time functionB.
No.1 1 time functionB.
...
但我期待它:
No.3 0 time functionB.
No.3 1 time functionB.
No.3 2 time functionB.
No.3 3 time functionB.
No.3 4 time functionB.
No.1 0 time functionB.
No.1 1 time functionB.
No.1 2 time functionB.
No.1 3 time functionB.
No.1 4 time functionB.
No.4 0 time functionB.
No.4 1 time functionB.
...
No.1 1 time functionD.
No.3 3 time functionC.
No.2 3 time functionD.
No.1 2 time functionD.
No.4 2 time functionC.
你可以像下面这样使用ExecutorService吗?
ExecutorService executorService = Executors.newFixedThreadPool(10);
public void functionA() {
synchronized (this) {
functionB();
}
executorService.submit(this::functionC);
executorService.submit(this::functionD);
}
不太优雅,但 B 完成后会在 C 和 D 之间交错。