1 ThreadPoolTaskExecutor

  1. @Configuration
  2. @EnableAsync
  3. public class TaskPoolConfig {
  4. @Bean
  5. public ThreadPoolTaskExecutor myTaskAsyncPool(){
  6. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  7. //核心线程池大小
  8. executor.setCorePoolSize(20);
  9. //最大线程数
  10. executor.setMaxPoolSize(50);
  11. //队列容量
  12. executor.setQueueCapacity(30);
  13. //活跃时间
  14. executor.setKeepAliveSeconds(60);
  15. //线程名字前缀
  16. executor.setThreadNamePrefix("MyExecutor-");
  17. //当pool已经到达max size的时候,如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
  18. executor.setThreadNamePrefix("thread-task-service-");
  19. executor.initialize();
  20. return executor;
  21. }
  22. }
  23. // 使用
  24. myTaskAsyncPool.execute(() -> {
  25. // todo...
  26. });

2 时间转换

  1. /**
  2. * ----------------------------------------- SimpleDateFormat 线程不安全 --------------------------
  3. */
  4. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
  5. // String 转 data
  6. Date date1 = simpleDateFormat.parse("2019-09-02 20");
  7. Date date2 = simpleDateFormat.parse("2019-09-02 21");
  8. System.out.println(simpleDateFormat.format(date1));
  9. // 相差几小时
  10. System.out.println((date2.getTime() - date1.getTime())/1000/3600);
  11. // UTC 转 String(data)
  12. Date date = new Date(date2.getTime());
  13. String dareString = simpleDateFormat.format(date);
  14. System.out.println(dareString);
  15. /**
  16. * ---------------------------------- LocalDateTime 线程安全--------------------------------
  17. * ---------------------String----TimeStamp----LocalDataTime----LocalData------------------
  18. */
  19. public static LocalDateTime stringToLocalDateTime(String dateString, String pattern){
  20. return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(pattern));
  21. }
  22. public static LocalDate stringToLocalDate(String dateString, String pattern){
  23. return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(pattern));
  24. }
  25. public static long stringToTimeStamp(String dateString,String pattern){
  26. if(pattern.contains("HH")){
  27. return localDateTimeToTimeStamp(stringToLocalDateTime(dateString,pattern));
  28. }
  29. return localDateToTimeStamp(stringToLocalDate(dateString,pattern));
  30. }
  31. public static String localDateTimeToString(LocalDateTime time,String pattern){
  32. return DateTimeFormatter.ofPattern(pattern).format(time);
  33. }
  34. public static long localDateTimeToTimeStamp(LocalDateTime time){
  35. return time.toEpochSecond(ZoneOffset.of("+8"));
  36. }
  37. public static long localDateToTimeStamp(LocalDate time){
  38. return time.atStartOfDay().toEpochSecond(ZoneOffset.of("+8"));
  39. }
  40. public static String localDateToString(LocalDate time,String pattern){
  41. return DateTimeFormatter.ofPattern(pattern).format(time);
  42. }
  43. public static LocalDateTime timeStampToLocalDateTime(long timeStamp){
  44. return LocalDateTime.ofEpochSecond(timeStamp,0,ZoneOffset.ofHours(8));
  45. }
  46. public static LocalDate timeStampToLocalDate(long timeStamp){
  47. return Instant.ofEpochSecond(timeStamp).atOffset(ZoneOffset.of("+8")).toLocalDate();
  48. }
  49. public static String timeStampToString(long timeStamp,String pattern){
  50. return localDateTimeToString(timeStampToLocalDateTime(timeStamp),pattern);
  51. }

3 Double 取消科学计数法

  1. double d = 112451254012.12485;
  2. NumberFormat nf = NumberFormat.getInstance();
  3. //设置保留多少位小数
  4. nf.setMaximumFractionDigits(20);
  5. // 取消科学计数法
  6. nf.setGroupingUsed(false);
  7. //返回结果
  8. System.out.println(nf.format(d));

4 Maven 项目打包

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.apache.maven.plugins</groupId>
  5. <artifactId>maven-compiler-plugin</artifactId>
  6. <version>3.1</version>
  7. </plugin>
  8. <plugin>
  9. <artifactId>maven-assembly-plugin</artifactId>
  10. <configuration>
  11. <archive>
  12. <manifest>
  13. <mainClass>com.cug.Main</mainClass>
  14. </manifest>
  15. </archive>
  16. <descriptorRefs>
  17. <descriptorRef>jar-with-dependencies</descriptorRef>
  18. </descriptorRefs>
  19. </configuration>
  20. <!--下面是为了使用 mvn package命令,如果不加则使用mvn assembly-->
  21. <executions>
  22. <execution>
  23. <id>make-assemble</id>
  24. <phase>package</phase>
  25. <goals>
  26. <goal>single</goal>
  27. </goals>
  28. </execution>
  29. </executions>
  30. </plugin>
  31. </plugins>
  32. </build>

5 执行可执行程序

  1. String path = System.getProperty("user.dir")+"\\main.exe";
  2. @Test
  3. public void test1() throws IOException {
  4. BufferedReader bufferedReader;
  5. Process proc = Runtime.getRuntime().exec(path);
  6. // 获取子进程的错误流,并打印
  7. bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
  8. OutputStreamWriter outputStreamWriter = new OutputStreamWriter(proc.getOutputStream());
  9. String line;
  10. while ((line = bufferedReader.readLine()) != null) {
  11. System.out.println(line);
  12. }
  13. }
  14. @Test
  15. public void test2() throws IOException {
  16. Process p = new ProcessBuilder().command(path,"--url","http://localhost:8889").start();
  17. InputStream i = p.getInputStream();
  18. Scanner scanner = new Scanner(i);
  19. while (scanner.hasNextLine()){
  20. System.out.println(scanner.nextLine());
  21. }
  22. }

6 扫描线填充算法

https://blog.csdn.net/wodownload2/article/details/52154207
  1. package com.cug.web;
  2. import javax.swing.*;
  3. import java.awt.*;
  4. import java.util.ArrayList;
  5. import java.util.Collections;
  6. public class FillTest extends JFrame {
  7. private ArrayList<Edge> edgeTable = new ArrayList<>();
  8. private int getYmin() {
  9. int yMin = edgeTable.get(0).y1;
  10. for (Edge edge : edgeTable) {
  11. if (edge.y1 < yMin)
  12. yMin = edge.y1;
  13. }
  14. return yMin;
  15. }
  16. private int getYmax() {
  17. int yMax = edgeTable.get(0).y1;
  18. for (Edge edge : edgeTable) {
  19. if (edge.y1 > yMax)
  20. yMax = edge.y1;
  21. }
  22. return yMax;
  23. }
  24. private boolean isActive(Edge edge, int currentY) {
  25. return edge.y1 < currentY && currentY <= edge.y2 || edge.y1 >= currentY && currentY > edge.y2;
  26. }
  27. private void updateActiveEdges(ArrayList<Edge> activeEdges, int y) {
  28. for (Edge edge : edgeTable) {
  29. if (isActive(edge, y)) {
  30. if (!activeEdges.contains(edge)) {
  31. activeEdges.add(edge);
  32. }
  33. } else {
  34. activeEdges.remove(edge);
  35. }
  36. }
  37. }
  38. private void findIntersections(ArrayList<Integer> intersections, ArrayList<Edge> activeEdges, int currentY) {
  39. intersections.clear();
  40. for (Edge edge : activeEdges) {
  41. int x = edge.x1 + ((currentY - edge.y1) * (edge.dx)) / (edge.dy);
  42. intersections.add(x);
  43. }
  44. }
  45. public void fill() {
  46. ArrayList<Edge> activeEdges = new ArrayList(10);
  47. ArrayList<Integer> intersections = new ArrayList(20);
  48. Graphics g = getGraphics();
  49. g.setColor(Color.red);
  50. // x1,y1,x2,y2
  51. edgeTable.add(new Edge(100, 100, 100, 600));
  52. edgeTable.add(new Edge(100, 600,500,400));
  53. edgeTable.add(new Edge(500,400, 100, 100));
  54. int yMin = getYmin();
  55. int yMax = getYmax();
  56. for (int y = yMin; y < yMax; y++) {
  57. updateActiveEdges(activeEdges, y);
  58. findIntersections(intersections, activeEdges, y);
  59. Collections.sort(intersections);
  60. for (int i = 0; i < intersections.size(); i += 2) {
  61. int x1 = intersections.get(i);
  62. if (i + 1 >= intersections.size()){
  63. break;
  64. }
  65. int x2 = intersections.get(i + 1);
  66. g.drawLine(x1, y, x2, y);
  67. }
  68. }
  69. }
  70. public static void main(String[] args) {
  71. FillTest s = new FillTest();
  72. s.setSize(800, 800);
  73. s.setVisible(true);
  74. s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  75. s.fill();
  76. }
  77. }
  78. class Edge {
  79. int x1, y1, x2, y2, dx, dy;
  80. Edge(int x1, int y1, int x2, int y2) {
  81. this.x1 = x1;
  82. this.y1 = y1;
  83. this.x2 = x2;
  84. this.y2 = y2;
  85. this.dx = x2 - x1;
  86. this.dy = y2 - y1;
  87. }
  88. }

7 JDK动态代理(只能代理实现了接口的类)

  1. import org.junit.jupiter.api.Test;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.InvocationTargetException;
  4. import java.lang.reflect.Method;
  5. import java.lang.reflect.Proxy;
  6. public class ProxyTest {
  7. interface SmsService {
  8. void send(String message,String msg);
  9. }
  10. static class SmsServiceImpl implements SmsService {
  11. public void send(String message,String msg) {
  12. System.out.println("send message:" + message + "---" + msg);
  13. }
  14. }
  15. static class DebugInvocationHandler implements InvocationHandler {
  16. /**
  17. * 代理类中的真实对象
  18. */
  19. private final Object target;
  20. public DebugInvocationHandler(Object target) {
  21. this.target = target;
  22. }
  23. @Override
  24. public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
  25. // 调用方法之前,添加自己的操作
  26. System.out.println("before method " + method.getName());
  27. Object result = method.invoke(target, args);
  28. // 调用方法之后,添加自己的操作
  29. System.out.println("after method " + method.getName());
  30. return result;
  31. }
  32. }
  33. @Test
  34. void test1(){
  35. SmsServiceImpl smsService1 = new SmsServiceImpl();
  36. SmsService smsService = (SmsService) Proxy.newProxyInstance(
  37. // 目标类的类加载
  38. smsService1.getClass().getClassLoader(),
  39. // 代理需要实现的接口,可指定多个
  40. smsService1.getClass().getInterfaces(),
  41. new DebugInvocationHandler(smsService1));
  42. smsService.send("java","test");
  43. }
  44. }

8 cglib 动态代理

  1. <dependency>
  2. <groupId>cglib</groupId>
  3. <artifactId>cglib</artifactId>
  4. <version>3.3.0</version>
  5. </dependency>
  1. import net.sf.cglib.proxy.Enhancer;
  2. import net.sf.cglib.proxy.MethodInterceptor;
  3. import net.sf.cglib.proxy.MethodProxy;
  4. import org.junit.jupiter.api.Test;
  5. import java.lang.reflect.Method;
  6. public class ProxyCglibTest {
  7. static class SmsService {
  8. public void send(String message,String msg) {
  9. System.out.println("send message:" + message + "---" + msg);
  10. }
  11. }
  12. /**
  13. * 自定义MethodInterceptor
  14. */
  15. static class DebugMethodInterceptor implements MethodInterceptor {
  16. /**
  17. * @param o 代理对象(增强的对象)
  18. * @param method 被拦截的方法(需要增强的方法)
  19. * @param args 方法入参
  20. * @param methodProxy 用于调用原始方法
  21. */
  22. @Override
  23. public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
  24. //调用方法之前,我们可以添加自己的操作
  25. System.out.println("before method " + method.getName());
  26. Object object = methodProxy.invokeSuper(o, args);
  27. //调用方法之后,我们同样可以添加自己的操作
  28. System.out.println("after method " + method.getName());
  29. return object;
  30. }
  31. }
  32. @Test
  33. void test1(){
  34. Class<SmsService> smsServiceClass = SmsService.class;
  35. // 创建动态代理增强类
  36. Enhancer enhancer = new Enhancer();
  37. // 设置类加载器
  38. enhancer.setClassLoader(smsServiceClass.getClassLoader());
  39. // 设置被代理类
  40. enhancer.setSuperclass(smsServiceClass);
  41. // 设置方法拦截器
  42. enhancer.setCallback(new DebugMethodInterceptor());
  43. // 创建代理类
  44. SmsService smsService = (SmsService) enhancer.create();
  45. smsService.send("java","test");
  46. }
  47. }

9 反射

  1. public class TargetObject {
  2. private String value;
  3. public TargetObject() {
  4. value = "targetObject";
  5. }
  6. public void publicMethod(String s) {
  7. System.out.println("publicMethod " + s);
  8. }
  9. private void privateMethod() {
  10. System.out.println("privateMethod " + value);
  11. }
  12. }
  13. public class Main {
  14. public static void main(String[] args) throws Exception {
  15. /**
  16. * 获取 TargetObject 类的 Class 对象并且创建 TargetObject 类实例
  17. */
  18. Class<?> targetClass = Class.forName("com.cug.TargetObject");
  19. TargetObject targetObject = (TargetObject) targetClass.newInstance();
  20. /**
  21. * 获取 TargetObject 类中定义的所有方法
  22. */
  23. Method[] methods = targetClass.getDeclaredMethods();
  24. for (Method method : methods) {
  25. System.out.println(method.getName());
  26. }
  27. /**
  28. * 获取指定方法并调用
  29. */
  30. Method publicMethod = targetClass.getDeclaredMethod("publicMethod",String.class);
  31. publicMethod.invoke(targetObject, "targetObject");
  32. /**
  33. * 获取指定参数并对参数进行修改
  34. */
  35. Field field = targetClass.getDeclaredField("value");
  36. //为了对类中的参数进行修改我们取消安全检查
  37. field.setAccessible(true);
  38. field.set(targetObject, "modify");
  39. /**
  40. * 调用 private 方法
  41. */
  42. Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
  43. //调用 private 方法,取消安全检查
  44. privateMethod.setAccessible(true);
  45. privateMethod.invoke(targetObject);
  46. }
  47. }

10 回调函数

public class CallBackTest {

    interface CallBack {
        void send(String msg);
    }

    static class Callback1 implements CallBack{
        @Override
        public void send(String msg) {
            System.out.println("Callback1 : " + msg);
        }
    }

    static class Callback2 implements CallBack{
        @Override
        public void send(String msg) {
            System.out.println("Callback2 : " + msg);
        }
    }

    public void execute(CallBack callBack) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            callBack.send("i = " + i);
            TimeUnit.SECONDS.sleep(1);
        }
    }

    @Test
    void  test1() throws InterruptedException {
        execute(new CallBack() {
            @Override
            public void send(String msg) {
                System.out.println("匿名 : " + msg);
            }
        });
        execute(new Callback1());
        execute(new Callback2());
    }
}