java - 改进类的多个实例访问同一类中多个同步函数的工作流程

标签 java multithreading

我是多线程编程的新手。我在理解类的多个实例的同步方法访问行为时遇到问题。

在下面的代码中我尝试实现等待和轮询机制。我在哪里等待一项服务的响应一段时间,如果该服务在这段时间内返回响应,我将返回。

在此我实现了两个同步块(synchronized block)。我可以理解两个线程不能同时访问同步方法。只有在这里,如果同时创建和调用 WaitAndPoll 类的多个实例,我会感到困惑。

每个实例都会一一执行。如果是这样的话,在这种情况下会严重影响性能,任何人都可以建议如何简化它吗?

等待和轮询:

public class WaitAndPoll {

    Model model;
    OSBService osbService;

    WaitAndPoll(Model model, OSBService th1){
        this.model = model;
        this.osbService=th1;
    }

    // Prints a string and waits for consume()
    public void waitingForOSBResponse()throws InterruptedException
    {

        synchronized(this)
        {
            System.out.println("waitingForOSBResponse thread running "+this.model.str);


            this.osbService.start();
            wait();

            if(this.model.str==null) { // checking the response is still null if so calling java function
                this.osbService.interrupt(); //This will interupt osb service thread
                System.out.println(" Calling the java function");
            }else{
                System.out.println(" Response successfully returned from the OSBService :: "+this.model.str);
            }
        }
    }

    //Polling for every 1 second
    public void pollingOSBResponse()throws InterruptedException
    {

        Thread.sleep(200);

        synchronized(this)
        {

            int count=0;
            while(this.model.str == null && count<3){
                wait(1000);
                System.out.println("wating for the modification");
                ++count;
            }
            System.out.println("Polling completed");
            notify();

        }
    }
}

OSB服务:

import java.util.Date;

public class OSBService extends Thread{


    Model model;

    OSBService(Model model){
        this.model= model;
    }

    public void run(){
        System.out.println("calling the osb webservice:: "+this.model.str);
        try {

            Thread.sleep(5000); //Simulating the wating period for the response
            this.model.str="modified";
            System.out.println("called the osb webservice:: "+this.model.str);

        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            System.err.println("OSB service interrupted because of longer time for response ::: "+this.model.str+" :: "+new Date().toString());
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

主类:

public class Main
{  
    public static void main(String[] args) throws InterruptedException  
    {

        Model model = new Model();
        model.str=null;
        OSBService osbService = new OSBService(model);
        final WaitAndPoll waitAndPoll = new WaitAndPoll(model,osbService);


        //Calling the OSB service and waiting for its response
        Thread t1 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    waitAndPoll.waitingForOSBResponse();
                }
                catch(InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        });

        //Polling whether the osb reponse received or not
        Thread t2 = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    waitAndPoll.pollingOSBResponse();
                }
                catch(InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();

       t1.join();
       t2.join();
    }


}

最佳答案

如果创建了多个实例,则这些方法将尝试在 WaitAndPoll 类的不同实例上获取同步块(synchronized block)中的互斥锁。 如果您将不同的实例传递给线程,则无法保证哪个线程将首先执行同步块(synchronized block)。

关于java - 改进类的多个实例访问同一类中多个同步函数的工作流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56295816/

相关文章:

c++ - 多态对象销毁和并发

c++ - 带互斥量的多线程输入不平滑(如预期)

java - 在 Java 中强制进行虚假唤醒

java - 在 AccessibilityServiceInfo 上设置多个 eventType

java - 非面向对象方法引入面向对象方法有什么问题

java - 按主机名设置 vaadin 主题

java - Android Studio 3.0 金丝雀 8 : Advanced profiling is unavailable for the selected process

java - 用 jar 打开时图像不可见。升级 javaFx 后创建新图像需要完整目录

c++ - 如何处理 QThread 上的事件?

c++ - 了解 qthread 子类的运行方法和线程上下文