我们可以在同一方法中使用多个同步块吗

时间:2019-10-15 04:23:41

标签: java multithreading synchronization

我正在使用执行程序框架进行多线程处理,并且对同步块执行有些困惑。有人可以建议如果以下代码在同步方面存在问题,如果可以,我该如何改善呢?谢谢。

public class ProcessDemo {

    private ExecutorService executorService = Executors.newCachedThreadPool();
    @SuppressWarnings("InfiniteLoopStatement")
    public void startProcess(){

        do {
            // making connection with clients
            ThreadingDemo thread = new ThreadingDemo(clientDemo);
            executorService.execute(thread);
        } while (true);
    }
}
public class ThreadingDemo implements Runnable{

    private ClientDemo clientDemo;

    ThreadingDemo(ClientDemo clientDemo){
        this.clientDemo = clientDemo;
    }
    public void run(){
        if(someCodition){
            synchronized (ThreadingDemo.class){
                clientDemo.show();
            }
        }

        synchronized (ThreadingDemo.class){
            myMethod1();
        }
    }

    private void myMethod1() {
        clientDemo.start();
        clientDemo.show();
    }
}

public class ClientDemo {

    void start(){

    }
    void show(){

    }
}

0 个答案:

没有答案
相关问题