There is a class that has a method for adding messages to be sent, and there is a method running in a separate thread (run) that sends messages if they are in a queue. The problem is when I add letters to the queue inside the run method it is always empty. I establish a connection between the threads.

public class send extends Thread { Queue<byte[]> arr; send() { arr=new LinkedList<>(); } public void set(byte[] a) { arr.add(a); } public void run() { while(true) { if(arr.size()>0) { //Тут идет отправка сообщений } } } } public class Main(String[] eq) { send va=new send(); va.start(); String letter="Hello world"; va.set(letter.getBytes()); } 

    1 answer 1

    I think the problem is the lack of synchronization.

    Without it, the optimizer, for example, has the right to assume that since there is no addition to arr in the arr , it will always be empty.

    In addition, your code chases the idle loop while waiting for a message. This is wrong, so do not. You should use the producer / consumer pattern (for example, there is an example implementation here.)