简单多线程添加任务按照添加顺序消费

在多线程操作同一个队列时,A线程添加数据,B线程消费数据,需要保证按照添加顺序消费,又需要是线程安全,不允许多个线程消费同一个

使用ConcurrentLinkedQueue保证线程安全,又是队列


一个线程添加,一个线程消费

package com.nsk666.iterator;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

public class IteratorTest {

    private Queue<Student> list = new ConcurrentLinkedQueue<>();

    public static void main(String[] args) throws InterruptedException {
        IteratorTest iteratorTest = new IteratorTest();
        iteratorTest.addStr();
        iteratorTest.testIterator();
    }

    private void testIterator() {
        new Thread(() -> {
            while (true) {
                System.out.println(list);
                if (!list.isEmpty()) {
                    try {
                        Student element = list.poll();
                        System.out.println(element.getName());
                        Thread.sleep(1);
                    } catch (Exception e) {
                        System.out.println("error");
                    }
                }
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

    }

    private void addStr() {
        new Thread(new Runnable() {
            int sleep = 1;
            @Override
            public void run() {
                for (int i = 0 ;i <10000;i++){
                    try {
                        Thread.sleep(sleep);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    list.offer(new Student(i+""));
                    System.out.println("add "+i);
                }
            }
        }).start();


    }

}

class Student {
    private String name;

    public Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

img_tc_1624341702974274196.png