自己写的异步多线程队列

  1. 使用 synchronized版本
public abstract class MessageQueue2<T> {
    private LinkedList<T> queue = new LinkedList<T>();

    public MessageQueue2() {
    }

    public void start() {
        new Thread(new MessageThread()).start();
    }

    public abstract void takeMessage(T message);

    public void pushMessage(T message) {
        synchronized (queue) {
//            Log.e("queue", "push:" + message.toString());
            this.queue.offer(message);
            this.queue.notify();
//            Log.e("queue", "notify:");
        }
    }

    class MessageThread implements Runnable {
        public void run() {
            synchronized (queue) {
                while (true) {
//                    Log.e("queue", "while");
                    if (!queue.isEmpty()) {
                        T message = queue.poll();
//                        Log.e("queue", "takemess:"+message.toString());
                        takeMessage(message);
                    } else {
                        try {
//                            Log.e("queue", "thread:wait");
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
  1. 使用ReentrantLock版本
public abstract class MessageQueue<T> {
    protected LinkedList<T> queue = new LinkedList<T>();
    protected ReentrantLock lock = new ReentrantLock();
    private Condition emptySignal = lock.newCondition();
//    private byte[] lock = new byte[0];
    private int threadCount = 1;
    private boolean disposeFlag = false;

    public MessageQueue() {
    }

    public void setThreadCount(int count) {
        this.threadCount = count;
    }

    protected LinkedList<T> getQueue(){
        return this.queue;
    }

    public void start() {
        ConsumeThread thread = new ConsumeThread();
        for (int i = 0; i < this.threadCount; i++) {
            new Thread(thread).start();
        }
    }

    public abstract void takeMessage(T message);

    public void pushMessage(T message) {
        if (!disposeFlag) {
            try {
                this.lock.lock();
//                Log.e("queue", "push:" + message.toString());
                this.queue.offer(message);
                this.emptySignal.signalAll();
            } finally {
                this.lock.unlock();
                // Log.e("queue", "notify:");
            }
        }
    }

    public boolean containsMessage(T message) {
        boolean flag = false;
        try {
            this.lock.lock();

            flag = this.queue.contains(message);
        } finally {
            this.lock.unlock();
        }
        return flag;
    }

    public void dispose() {
//        Log.e("messqueue", "dispose");
        try {
            this.lock.lock();
            this.emptySignal.signalAll();
        } finally {
            this.lock.unlock();
            // Log.e("queue", "notify:");
        }
//        this.emptySignal.signal();
        this.disposeFlag = true;
    }

    class ConsumeThread implements Runnable {
        public void run() {
            while (!disposeFlag) {
                T message = null;
//                Log.e("queue", "while");
                try {
                    lock.lock();
                    if (!queue.isEmpty()) {
                        message = queue.poll();
                    } else {
//                        Log.e("queue", "thread:wait");
                        emptySignal.await();
                    }
                } catch (InterruptedException e) {
//                    Log.e("messagequeue wait", Log.getStackTraceString(e));
                } finally {
                    lock.unlock();
                }
                if (message != null) {
//                    Log.e("queue", "takemess:" + message.toString());
                    takeMessage(message);
                }
            }
        }
    }
}

2016-12-22更新版本
使用了blockingqueue封装

public class MessageFactory {
    private BlockingQueue messageQueue = new LinkedBlockingDeque<>();
    private static ConcurrentHashMap<Object,MessageAction> cache = new ConcurrentHashMap<>();
    private static MessageFactory instance = new MessageFactory();
    private boolean stop;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private MessageFactory(){
        this.start();
    }

    public static MessageFactory instance(){
        return instance;
    }

    public<T> void put(T message,MessageAction<T> action){
        try {
            this.messageQueue.put(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.cache.put(message,action);
    }

    private<T> void start(){
        new Thread(() -> {
            while (!stop) {
                T message = null;
                try {
                    message = (T)messageQueue.take();
                    //为了防止此时cache.put还没有完成
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                MessageAction<T> action = cache.get(message);
                if (action == null){
                    continue;
                }
                action.take(message);
            }
            this.messageQueue.clear();
        }).start();
    }

    public void dispose(){
        this.stop = true;
        try {
            //通过put来唤醒queue阻塞线程,退出循环
            this.messageQueue.put(" ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Python 的线程是用来支持多任务的,可以用来提升程序的性能。但是由于 Python 的解释器是使用解释执行的,它的线程并不能真正地并发执行,因此也不能用来支持异步编程。 Python 中有提供了一些模块来支持异步编程,例如 asyncio 和 twisted 等。 队列是一种数据结构,可以用来存储数据并支持 FIFO(先进先出)的数据访问方式。Python 标准库中有一个 queue 模块,提供了多种队列的实现,可以用来在线程之间传递数据。 ### 回答2: Python中的线程异步队列是一些常用的编程概念和功能。 线程是一种轻量级的执行单元,使得程序可以同时执行多个任务。在Python中,我们可以使用threading模块来创建和管理线程线程可以并发地执行,从而提高程序的执行效率。 异步编程是一种编高效、非阻塞代码的技术。Python中的异步编程可以通过asyncio模块来实现。使用异步编程的优势是可以同时执行多个任务,而不需要等待一个任务完成后再执行下一个任务。 队列是一种数据结构,用于存储和管理数据。在Python中,我们可以使用queue模块来创建和操作队列队列可以用于在线程之间进行数据传输、协调和同步操作。 Python中的线程异步队列经常一起使用,以实现高效的并发编程。我们可以使用线程创建多个并发执行的任务,使用异步编程提高任务的执行效率,同时使用队列进行任务之间的数据传输和协调。 例如,我们可以创建一个线程池,每个线程异步地执行任务,并将任务的结果存储在队列中。其他线程可以从队列中获取任务结果,并进行后续的处理。这样可以充分利用计算资源,并提高程序的执行效率。 总之,Python中的线程异步队列是一些常用的编程概念和功能,它们可以帮助我们实现高效的并发编程。通过合理地使用这些功能,我们可以提高程序的执行效率和性能。 ### 回答3: Python中的线程(Thread)是一种用于实现多线程编程的机制。线程可以并发执行,相较于单线程,可以提高程序的执行效率。 Python中的异步(Asynchronous)编程是一种非阻塞的编程模式,可以在等待某个操作完成时继续执行其他任务,而不需要等待阻塞的结果返回。 队列(Queue)是一种数据结构,用于在多线程/异步环境中传递和共享数据。Python中提供了Queue模块,包括三种不同类型的队列:Queue、LifoQueue和PriorityQueue。这些队列可以安全地在多个线程/异步任务之间传递数据。 在Python中,线程队列常常结合使用,可以实现多线程间的通信和数据共享。线程可以通过将数据放入队列中,然后其他线程队列中获取数据来实现数据传递。这种机制确保了线程之间的同步和安全性。 另外,在使用异步编程时,可以使用队列来存储需要异步执行的任务。通过将任务放入队列中,然后使用异步框架/库来处理队列中的任务,可以实现高效的异步编程。 总结来说,Python的线程异步队列是三个在多线程/异步编程中常用的概念。线程提供了并发执行的机制,异步可以实现非阻塞的编程方式,而队列可以实现线程/异步任务间的数据传递和共享。结合使用这些概念,可以实现高效、安全的多线程/异步编程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值