Java8-并行流的使用

Java8中的并行流使用

public class StreamTest {
    public List<Person> constructPersons() {

        List<Person> persons = new ArrayList<Person>();
        for (int i = 0; i < 5; i++) {
            Person p = new Person(i, "name" + i, "sex" + i, i);
            persons.add(p);
        }
        return persons;
    }

    /**
     * for
     *
     * @param persons
     */
    public void doFor(List<Person> persons) {
        long start = System.currentTimeMillis();

        for (Person p : persons) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println(p.name);
        }

        long end = System.currentTimeMillis();
        System.out.println("doFor cost:" + (end - start));
    }

    /**
     * 顺序流
     *
     * @param persons
     */
    public void doStream(List<Person> persons) {
        long start = System.currentTimeMillis();

        persons.stream().forEach(x -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println(x.name);
        });

        long end = System.currentTimeMillis();
        System.out.println("doStream cost:" + (end - start));
    }

    /**
     * 并行流
     *
     * @param persons
     */
    public void doParallelStream(List<Person> persons) {

        long start = System.currentTimeMillis();

        persons.parallelStream().forEach(x -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println(x.name);
        });

        long end = System.currentTimeMillis();

        System.out.println("doParallelStream cost:" + (end - start));
    }

    public static void main(String[] args) {
        StreamTest streamTest = new StreamTest();
        List<Person> personList = streamTest.constructPersons();
        streamTest.doFor(personList);
        streamTest.doStream(personList);
        streamTest.doParallelStream(personList);
    }

    public static void main1(String[] args) {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        long id = snowflake.nextId();
        List<String> orderNos = Collections.synchronizedList(new ArrayList<String>());
        IntStream.range(0,10000000).parallel().forEach(i->{
            orderNos.add(snowflake.nextId()+"");
        });
        System.out.println(orderNos.size());
    }
posted @ 2023-06-14 13:34  ByteX  阅读(36)  评论(0)    收藏  举报