Run Handler messages in a background thread

前端 未结 5 1955
失恋的感觉
失恋的感觉 2020-12-04 19:09

I want to run some Runnable in a background thread. I want to use Handler because it\'s convenient for delays. What I mean is

handler.post(runnable, delay);
         


        
5条回答
  •  北海茫月
    2020-12-04 20:11

    Not clear what you mean by Handler.

    It sounds like you need a thread that is fed processes to perform by a queue. You would probably benefit from investigating Executors here but here's a simple two-thread pair that communicate through a queue.

    public class TwoThreads {
      public static void main(String args[]) throws InterruptedException {
        System.out.println("TwoThreads:Test");
        new TwoThreads().test();
      }
      // The end of the list.
      private static final Integer End = -1;
    
      static class Producer implements Runnable {
        final Queue queue;
    
        public Producer(Queue queue) {
          this.queue = queue;
        }
    
        @Override
        public void run() {
          try {
            for (int i = 0; i < 1000; i++) {
              queue.add(i);
              Thread.sleep(1);
            }
            // Finish the queue.
            queue.add(End);
          } catch (InterruptedException ex) {
            // Just exit.
          }
        }
      }
    
      static class Consumer implements Runnable {
        final Queue queue;
    
        public Consumer(Queue queue) {
          this.queue = queue;
        }
    
        @Override
        public void run() {
          boolean ended = false;
          while (!ended) {
            Integer i = queue.poll();
            if (i != null) {
              ended = i == End;
              System.out.println(i);
            }
          }
        }
      }
    
      public void test() throws InterruptedException {
        Queue queue = new LinkedBlockingQueue<>();
        Thread pt = new Thread(new Producer(queue));
        Thread ct = new Thread(new Consumer(queue));
        // Start it all going.
        pt.start();
        ct.start();
        // Wait for it to finish.
        pt.join();
        ct.join();
      }
    }
    

提交回复
热议问题