Write your own hair a wait (), notify small case

Because the mailbox to send very slow, generally better than a few seconds to send an e-mail QQ, I wrote a mail queue, with a thread to send mail, here's a simulated case.

This case simulates a mail sending process. EmailQueueSendUtils contains a message queue, after the start of the EmailQueueSendUtils, mail queue will automatically detect whether there are messages, if any, will be sent, otherwise it will wait for a new message to notify blocked thread.

Here Insert Picture Description

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class Test2{

    public static void main(String[] args) throws InterruptedException {
        EmailQueueSendUtils emailQueueSendUtils = new EmailQueueSendUtils(new ArrayList<>());

        new Thread(emailQueueSendUtils, "1").start();
        new Thread(emailQueueSendUtils, "2").start();

        for (int i = 0; i < 50; i++) {
            emailQueueSendUtils.addEmailTask(i);
        }
        TimeUnit.SECONDS.sleep(10);
        System.exit(0);
    }
}

class EmailQueueSendUtils implements Runnable{
    private final List<Integer> emailEntityList;

    public EmailQueueSendUtils(List<Integer> emailEntityList){
        this.emailEntityList = emailEntityList;
    }

    @Override
    public void run() {

        while (true){
            System.out.println("进入线程"+Thread.currentThread().getName());
            synchronized (emailEntityList){
                //是否有邮件
                if(emailEntityList.size()>0){
                    while(emailEntityList.size()>0) {
                        Integer emailEntity = emailEntityList.remove(0);
                        System.out.println(Thread.currentThread().getName() + ", " + emailEntity + ", size: " + emailEntityList.size());
                    }
                    //输出完,等待
                    try {
                        emailEntityList.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        emailEntityList.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

    }

    public void addEmailTask(Integer emailEntity){
        synchronized (emailEntityList) {
            System.out.println("NUM: "+emailEntity+", 线程:"+Thread.currentThread().getName());
            emailEntityList.add(emailEntity);
            emailEntityList.notify();
        }
    }
}
Published 28 original articles · won praise 3 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_34291570/article/details/105276028