A
A
artshelom2017-06-21 11:37:05
Java
artshelom, 2017-06-21 11:37:05

How to access a method in order?

public class SeleniumBufferead implements Runnable {
    private void send() throws Exception{
//Тут ещё другой код коонечно
       sendMessages.send("каккие-то числа", "Сообщение");
 Thread.sleep(1000000);
    }

    @Override
    public void run() {
        try {
            this.send();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

And there is an appeal to this class. Like new Thread(new SeleniumBufferead ()).start()
How to do it, if several threads call this method at the same time, then a queue appears. While one thread does not finish, the other will not start working with it
Through synchronized??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2017-06-21
@artshelom

synchronized method is synchronized on this. Won't fit. For example, you can pass everywhere the object on which you want to synchronize.

public class SeleniumBufferead implements Runnable {
    private final Object lock;
    public SeleniumBufferead(Object lock) {
        this.lock = lock;
    }
    private void send() {
        synchronized(lock) {
             //code
        }
    }
}
.....
final Object lock = new Object();
new Thread(new SeleniumBufferead(lock)).start();
new Thread(new SeleniumBufferead(lock)).start();

In general, I advise you to read concurrency in practice .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question