[英]How to synchronized one method when parallelStream call in Java?
I want to Synchronize functionB.我想同步功能 B。 I mean, when some Attriute object call functionA, there are always just run one of object's functionB in the same time.
我的意思是,当某些属性 object 调用函数 A 时,总是同时运行对象的函数 B 之一。 But functionC and functionD in each object can do it after functionB finished by themselves.
但是每个object中的functionC和functionD可以在functionB自己完成之后再做。
I tried to add synchronized in function B, but it seems like not work.我尝试在 function B 中添加 synchronized,但似乎不起作用。
This is Attribute class:这是属性 class:
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);
}
}
After execute above code, the console show:执行以上代码后,控制台显示:
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.
...
But I expect it:但我希望它:
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.
Can you use ExecutorService like below.你能像下面这样使用 ExecutorService 吗?
ExecutorService executorService = Executors.newFixedThreadPool(10);
public void functionA() {
synchronized (this) {
functionB();
}
executorService.submit(this::functionC);
executorService.submit(this::functionD);
}
Not exactly elegant, but it will interleave between C and D after B is completed.算不上优雅,但B完成后会穿插在C和D之间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.