通过类的多个实例改善同一类访问中多个同步函数的工作流程

时间:2019-05-24 15:44:28

标签: java multithreading

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

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

在此,我实现了两个同步块。我可以理解,两个线程无法同时访问同步方法。在这里,只有同时创建和调用多个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();

        }
    }
}

OSBService:

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();
    }


}

1 个答案:

答案 0 :(得分:0)

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