线程使用例子

点击查看代码
package com.ly.fn.biz.ht.esign.expand.core.config;

import com.google.common.base.Joiner;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

public class AsyncConfigTest {
    public static void main(String[] args) {
        Executor executor = new AsyncConfig().asyncServiceExecutor();
        for (int i = 0; i < 10; i++) {
            final int index = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    if (index == 5 || index == 8) {
                        System.out.println(1 / 0);
                    }
                    System.out.println(">>>>>>>>>>>>>>" + index);
                }
            });
        }
        List<String> list = new ArrayList<>();
        list.add("444");
        list.add("333");
        System.out.println(Joiner.on(",").join(list));
        DecimalFormat df = new DecimalFormat("#,###.00");
        System.out.println("7321456987.258 =》" + df.format(new BigDecimal("0")));
    }


//   public static BigDecimal formatNumber(String str){
//        NumberFormat nf=NumberFormat.getPercentInstance();
//        try {
//            Number m=nf.parse(str);
//            return new BigDecimal(m.toString());
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return new BigDecimal(0);
//    }
}

点击查看代码
package com.ly.fn.biz.ht.esign.expand.core.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig {

    @Bean
    public Executor asyncServiceExecutor() {
        log.info("开始创建线程池");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(5);
        //配置最大线程数
        executor.setMaxPoolSize(5);
        //配置队列大小
        executor.setQueueCapacity(100);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-data-");
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

}

posted @ 2023-04-26 11:20  我的心儿  阅读(27)  评论(0)    收藏  举报