Android send data from main UI thread to another thread

后端 未结 3 1555
忘了有多久
忘了有多久 2021-02-10 02:44

I need to send some data from the main thread to another thread. I\'ve already read a lot of materials on threads, asynctasks and handlers but maybe they created some confusion

3条回答
  •  野性不改
    2021-02-10 02:57

    You could solve it using standard Java ways for consumer / producer problems, i.e. a BlockingQueue consumed by a thread and any amount of threads that produce data.

    public class SendingWorker {
        private final BlockingQueue sendQueue = new LinkedBlockingQueue();
        private volatile Socket socket;
    
        public void start() {
            thread.start();
        }
    
        public void stop() {
            // interrupt so waiting in queue is interrupted
            thread.interrupt();
            // also close socket if created since that can block indefinitely
            Socket socket = this.socket;
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        // adding to queues is thread safe
        public void send(Draw draw) {
            sendQueue.add(draw);
        }
    
        private final Runnable task = new Runnable() {
            @Override
            public void run() {
                try {
                    socket = new Socket(InetAddress.getLocalHost(), 8000);
                    OutputStream out = socket.getOutputStream();
                    while (true) {
                        Draw draw = sendQueue.take();
                        out.write(draw);
                        out.flush();
                    }
                } catch (Exception e) {
                    // handle 
                } finally {
                    // cleanup
                }
            }
        };
        private final Thread thread = new Thread(task);
    }
    

提交回复
热议问题