其他分享
首页 > 其他分享> > 咖啡汪日志——Stream流测试代码,私人笔记,请勿偷看!私人笔记,请勿偷看!私人笔记,请勿偷看!重要的事情说三遍

咖啡汪日志——Stream流测试代码,私人笔记,请勿偷看!私人笔记,请勿偷看!私人笔记,请勿偷看!重要的事情说三遍

作者:互联网

1.因式分解


import java.math.BigInteger;

/**
 * 进行因式分解的正确姿势
 * 每次进行分解的因子,都应该与上次最后一次进行缓存的因子相同
 * **
 *
 * @author: Yuezejian  Created in 2020/9/29 上午8:21
 * @modified By:
 */
public class CacheFactorizer {
    private BigInteger lastNumber;
    private BigInteger[] lastFactors;
    private long counts;
    private long cacheCounts;
    public synchronized long getCounts() {return this.counts;}
    public synchronized double getCacheCountsRatio() {
        return (double) cacheCounts / (double) counts;
    }
    //TODO:
    public void service(Integer counts) {
        BigInteger i = BigInteger.valueOf(counts);
        BigInteger[] factors = null;
        synchronized (this) {
            ++counts;
            if (i.equals(lastNumber)) {
                ++cacheCounts;
                factors = lastFactors.clone();
            }
        }
        if (factors == null) {
            factors = factors(i);
            synchronized (this) {
                lastNumber = i;
                lastFactors = factors.clone();
            }
        }

    }

    private BigInteger[] factors(BigInteger i) {
        return this.lastFactors;
    }

}

2.线程优先级


import java.util.stream.IntStream;

/**
 * 线程优先级
 * **
 *
 * @author: Yuezejian  Created in 2020/9/28 下午8:56
 * @modified By:
 */
public class ThreadRank {
    public static void main(String[] args) {
       Thread thread = new Thread(() -> {
           IntStream.rangeClosed(1,100).parallel().forEach( i -> {
               System.out.println(Thread.currentThread().getName());
           });
        },"线程1");
       thread.setPriority(Thread.MIN_PRIORITY);
       Thread thread1 = new Thread(() -> {
           IntStream.rangeClosed(1,20).parallel().forEach(i -> {
               System.out.println(Thread.currentThread().getName());
           });
        },"线程2");
       thread.start();
       thread.setDaemon(true);

    }
    //TODO:凡是“线程1”的都是同步执行的,其余的都是异步线程池执行的,1-7共7个执行线程,这是应为stream的并行流parallel使用的是实际可用的核心数-1,本汪猜应该是底层调用了Runtime.accessableProcessor()方法,然后减了一作为执行线程数,因为java中很多地方都是这么处理的,Runtime.accessableProcessor()方法返回的是实际可用的核心数,也包括现代cpu超线程技术所产生的虚拟内核。
    //线程1
    //ForkJoinPool.commonPool-worker-4
    //线程1
    //线程1
    //线程1
    //线程1
    //ForkJoinPool.commonPool-worker-1
    //线程1
    //ForkJoinPool.commonPool-worker-6
    //线程1
    //ForkJoinPool.commonPool-worker-2
    //ForkJoinPool.commonPool-worker-7
    //ForkJoinPool.commonPool-worker-4
    //ForkJoinPool.commonPool-worker-5
    //ForkJoinPool.commonPool-worker-3
    //ForkJoinPool.commonPool-worker-7
    //ForkJoinPool.commonPool-worker-2
    //线程1
    //ForkJoinPool.commonPool-worker-6
    //ForkJoinPool.commonPool-worker-1
}


import cn.hutool.core.lang.Snowflake;
import com.google.common.collect.Maps;
import com.tjxskj.taidacity.pojo.Coupon;
import org.assertj.core.util.Lists;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Predicate;
import java.util.stream.LongStream;

import static java.util.stream.Collectors.*;

/**
 * 缓存测试
 * **
 *
 * @author: Yuezejian  Created in 2020/10/5 下午3:29
 * @modified By:
 */
public class TestCache {
    public static final Snowflake  snow = new Snowflake(12,10);
    ConcurrentHashMap<Long, Coupon> cache;

    List<Coupon> list = Arrays.asList(new Coupon(1,new BigDecimal(2)),new Coupon(2,new BigDecimal(3)));
    List<Coupon> couponList = Lists.newArrayList(list);
    @Test
    public void addCache() {
       cache = LongStream.rangeClosed(1,10).boxed()
                .collect(toConcurrentMap(k -> snow.nextId(),v -> new Coupon(v,new BigDecimal(v)),
                        (o1, o2) -> o1,ConcurrentHashMap::new));
        Map<Long,String> map = Maps.newLinkedHashMap();
       cache.entrySet().forEach( entry -> {
//           System.out.println(entry.getKey());
//           System.out.println(entry.getValue());
       });
        Predicate<Integer> positiveNumber = i -> i > 0;
        Predicate<Integer> evenNumber = i -> i % 2 == 0;
        List<Integer> arr = Arrays.asList(1,2,-8,88,-9,-12,25,0,10);
        double[] arr1 = arr.stream().filter(i -> i > 0).sorted(Comparator.reverseOrder()).mapToDouble(Integer::doubleValue).toArray();

        Arrays.stream(arr1).forEach( i -> {
            System.out.println(i);
        });
        couponList.stream().forEach(i -> {
            System.out.println(i.toString());
        });
    }


}

import com.sun.codemodel.internal.JForEach;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.DisplayNameGeneration;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.stream.IntStream;

/**
 * Generate测试
 * **
 *
 * @author: Yuezejian  Created in 2020/9/30 上午8:48
 * @modified By:
 */
public class TestIntStream {

    //generate() 返回的是无限流,必须用limit去截取
    int sum = IntStream.generate(() -> 123).limit(1).sum();
    IntSupplier supplier = () -> 1;
    int sum1 = IntStream.generate(supplier).limit(1).sum();
    int sum2 = IntStream.rangeClosed(1,4).sum();
    int sum3 = IntStream.range(1,4).sum();
    int sum4 = IntStream.of(1,4,6,9).sum();
    int sum5 = IntStream.empty().sum();
    int sum6 = IntStream.builder().add(1).add(10).build().sum();
    long sum7 = IntStream.concat(IntStream.range(1,5),IntStream.rangeClosed(1,5)).sum();
    int sum8 = IntStream.iterate(1,i -> i + 1).limit(10).sum();


    @Test
    public void testIntStreamWithAssert() {
        Assert.assertEquals(123,sum);
        Assert.assertEquals(1,sum1);
        Assert.assertEquals(10,sum2);
        Assert.assertEquals(6,sum3);
        Assert.assertEquals(20,sum4);
        Assert.assertEquals(0,sum5);
        Assert.assertEquals(11,sum6);
        Assert.assertEquals(25,sum7);

    }

    @Test
    public void testInIntStream() {
        AtomicInteger count = new AtomicInteger();
        IntStream.iterate(2,(e) -> e).limit(10).forEach( i -> {
            count.addAndGet(i);
            System.out.println(count.get());
        });
        System.out.println("最终结果"+count);
    }


    public void testIterator() {
        Supplier<AtomicInteger> supplier = AtomicInteger::new;
    }

    ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> null);
}
import cn.hutool.core.lang.Snowflake;
import com.google.common.collect.Lists;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.IntSupplier;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toConcurrentMap;
import static java.util.stream.Collectors.toMap;

/**
 * stream操作测试
 * **
 *
 * @author: Yuezejian  Created in 2020/9/30 上午10:47
 * @modified By:
 */
public class TestStreamOperation {
    public static final Snowflake snowflake = new Snowflake(12,10);
    public static final int COUNT = 10;
    long sum = IntStream.of(1,2,3,4,6,7,8,9).filter(e -> e < 5).count();
    IntSupplier supplier = () -> 1 ;
    Supplier supplier1 = () -> new HashMap<>() ;

    public ConcurrentHashMap<String,Long> getList() {
        return LongStream.rangeClosed(1,COUNT)
                .boxed()
                .collect(toConcurrentMap(i -> UUID.randomUUID().toString(), identity(),
        (o1,o2) -> o1,ConcurrentHashMap::new));
    }

    public Map<String,Integer> getList1(List<Integer> list){
        return  list.stream()
                .collect(toMap(i -> snowflake.nextIdStr(), identity(),
                        (o1,o2) -> o1,HashMap::new));
    }

    public static void main(String[] args) {
        List<Integer> list = Lists.newArrayList();
        list = IntStream.builder().add(5).add(4).add(3).add(2).add(1).build().boxed().collect(Collectors.toList());
        TestStreamOperation test = new TestStreamOperation();
        Map<String,Integer> map = test.getList1(list);
        map.entrySet().forEach( i -> {
            System.out.println(i.getKey()+ "_"+i.getValue());
        });
        ConcurrentHashMap<String,Long> map1 = test.getList();
        map1.entrySet().forEach(i -> {
            System.out.println(i.getKey() +"_"+ i.getValue());
        });
        System.out.println();
    }

}
import com.fasterxml.jackson.databind.ser.Serializers;
import com.tjxskj.taidacity.tools.BaseTest;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.IntStream;

/**
 * 用来管理计数器的线程安全类
 * 说明:测试结果说明,多线程并发下,AtomicLong的确可以保证线程安全
 * **
 *
 * @author: Yuezejian  Created in 2020/9/28 下午5:04
 * @modified By:
 */
public class AutomicLongTest extends BaseTest {
    private final AtomicLong count = new AtomicLong(0);
    public static void main(String[] args) {
        AutomicLongTest automicLongTest = new AutomicLongTest();
        IntStream.rangeClosed(1,20).parallel().forEach( i -> {
                automicLongTest.add();
        });
        System.out.println(automicLongTest.count);

    }

    public void add () {
        count.incrementAndGet();
        log.info("这是第 {} 此进行+1操作",count);
    }
    //
    //7:23:02.382 logback [ForkJoinPool.commonPool-worker-3] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [ForkJoinPool.commonPool-worker-5] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [main] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [ForkJoinPool.commonPool-worker-2] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [ForkJoinPool.commonPool-worker-1] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [ForkJoinPool.commonPool-worker-4] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [ForkJoinPool.commonPool-worker-6] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.382 logback [ForkJoinPool.commonPool-worker-7] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 8 此进行+1操作
    //17:23:02.388 logback [main] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 10 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-6] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 10 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-7] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 11 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-1] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 12 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-3] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 13 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-1] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 14 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-7] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 15 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-4] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 16 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-2] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 17 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-5] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 18 此进行+1操作
    //17:23:02.388 logback [ForkJoinPool.commonPool-worker-4] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 20 此进行+1操作
    //17:23:02.388 logback [main] INFO  c.t.t.secondchapter.AutomicLongTest - 这是第 20 此进行+1操作
    //20
}

装箱和拆箱

    public ConcurrentHashMap<String,Long> getList() {
            return LongStream.rangeClosed(1,10)
                    .boxed()
                    .collect(Collectors.toConcurrentMap(i -> UUID.randomUUID().toString(), identity(),
            (o1,o2) -> o1,ConcurrentHashMap::new));
        }
    public void test() {
    //LongStream返回的是一个long类型的流
    //List<Long> list = Lists.newArrayLise<>();
         long[] lrr =  LongStream.rangeClosed(1,10).toArray();
        List<Long> list = Lists.newArrayList();
        List<Long> list1 = new ArrayList<>(128);
        list1 = Arrays.asList(19L,11L);
    }

标签:java,worker,ForkJoinPool,偷看,笔记,util,请勿,import,commonPool
来源: https://blog.csdn.net/weixin_42994251/article/details/108976167