簡體   English   中英

Java:回調到主線程

[英]Java: Callback to main Thread

如何使回調在“主線程”中執行?

@Test
void threadTest() throws InterruptedException {

    System.out.println("main thread:" + Thread.currentThread());

    new Thread(new AsyncTask(this::callback)).start();

    Thread.sleep(1100);
}

private void callback() {
    System.out.println("callback executed in: " + Thread.currentThread());
}

static class AsyncTask implements Runnable{
  private final  Runnable runnable;

    public AsyncTask(Runnable runnable) {
        this.runnable = runnable;
    }

    @Override
    public void run() {
        System.out.println("other thread: " + Thread.currentThread());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        this.runnable.run();
    }
}

您可以嘗試強制執行callback()特別是ExecutorService

class ConcTest {
    ExecutorService mainExecutor  = Executors.newFixedThreadPool(1);

    @Test
    void threadTest() throws Exception {
        mainExecutor.submit(() -> {
            System.out.println("main thread:" + Thread.currentThread());
            new Thread(new AsyncTask(mainExecutor, this::callback)).start();
            sleep(1100);
        }).get();
    }

    private void callback() {
        System.out.println("callback executed in: " + Thread.currentThread());
    }

    private static void sleep(int millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    static class AsyncTask implements Runnable{
        private final ExecutorService mainExecutor;
        private final Runnable runnable;

        public AsyncTask(ExecutorService mainExecutor, Runnable runnable) {
            this.mainExecutor = mainExecutor;
            this.runnable = runnable;
        }

        @Override
        public void run() {
            System.out.println("other thread: " + Thread.currentThread());
            try {
                Thread.sleep(1000);
                mainExecutor.submit(runnable).get();
            } catch (InterruptedException | ExecutionException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

這打印

main thread:Thread[pool-1-thread-1,5,main]
other thread: Thread[Thread-0,5,main]
callback executed in: Thread[pool-1-thread-1,5,main]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM