Java中的同步:线程创建但未同步执行?

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

有一个 Java 代码片段,涉及创建多个线程来执行一个方法,但我无法理解它的同步方面。这是代码:


public class SheepManager {
private int sheepCount = 0;
private void incrementAndReport() {
    System.out.print((++sheepCount)+" ");
}
public static void main(String[] args) {
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(20);
        SheepManager manager = new SheepManager();
        synchronized (manager){
            for(int i=0; i<10; i++)
                service.submit(() -> manager.incrementAndReport());
        }
    } finally {
        if(service != null) service.shutdown();
    }
}
}

在此代码中,我通过将 service.submit() 调用放在同步块中来同步线程的创建。但是,我不确定这是否保证线程将以同步方式执行。这种方法对于确保同步执行是否正确,或者是否有更好的方法来实现这一点?

任何有关如何正确同步此代码中创建的线程的执行的指导将不胜感激。

java multithreading synchronization threadpool
1个回答
0
投票

Output

This book they explain We’ve
synchronized the creation of the threads but not the execution of the threads.

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