Running code on the main thread from a secondary thread?

前端 未结 5 550
灰色年华
灰色年华 2020-12-05 10:23

This is a general Java question and not an Android one first off!

I\'d like to know how to run code on the main thread, from the context of a secondary thread. For e

5条回答
  •  甜味超标
    2020-12-05 10:42

    There is no universal way to just send some code to another running thread and say "Hey, you, do this." You would need to put the main thread into a state where it has a mechanism for receiving work and is waiting for work to do.

    Here's a simple example of setting up the main thread to wait to receive work from other threads and run it as it arrives. Obviously you would want to add a way to actually end the program and so forth...!

    public static final BlockingQueue queue = new LinkedBlockingQueue();
    
    public static void main(String[] args) throws Exception {
        new Thread(new Runnable(){
            @Override
            public void run() {
                final int result;
                result = 2+3;
                queue.add(new Runnable(){
                    @Override
                    public void run() {
                        System.out.println(result);
                    }
                });
            }
        }).start();
    
        while(true) {
            queue.take().run();
        }
    }
    

提交回复
热议问题