Create a simple queue with Java threads

前端 未结 4 666
终归单人心
终归单人心 2020-12-17 02:37

I\'m trying to create a simple queue with Java Thread that would allow a loop, say a for loop with 10 iterations, to iterate n (< 10) threads at a time and wait until tho

4条回答
  •  轮回少年
    2020-12-17 03:29

    Crate Logger.class :

    public class Logger extends Thread {
        List queue = new ArrayList();
        private final int MAX_QUEUE_SIZE = 20;
        private final int MAX_THREAD_COUNT = 10;
    
        @Override
        public void start() {
            super.start();
            Runnable task = new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        String message = pullMessage();
                        Log.d(Thread.currentThread().getName(), message);
                        // Do another processing
                    }
                }
            };
            // Create a Group of Threads for processing
            for (int i = 0; i < MAX_THREAD_COUNT; i++) {
                new Thread(task).start();
            }
        }
    
        // Pulls a message from the queue
        // Only returns when a new message is retrieves
        // from the queue.
        private synchronized String pullMessage() {
            while (queue.isEmpty()) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
            return queue.remove(0);
        }
    
        // Push a new message to the tail of the queue if
        // the queue has available positions
        public synchronized void pushMessage(String logMsg) {
            if (queue.size() < MAX_QUEUE_SIZE) {
                queue.add(logMsg);
                notifyAll();
            }
    
        }
    }
    

    Then insert bellow code in your main class :

    Logger logger =new Logger();
    logger.start();
    for ( int i=0; i< 10 ; i++) {
        logger.pushMessage(" DATE : "+"Log Message #"+i);
    }
    

提交回复
热议问题