1 ThreadPoolTaskExecutor
@Configuration
@EnableAsync
public class TaskPoolConfig {
@Bean
public ThreadPoolTaskExecutor myTaskAsyncPool(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程池大小
executor.setCorePoolSize(20);
//最大线程数
executor.setMaxPoolSize(50);
//队列容量
executor.setQueueCapacity(30);
//活跃时间
executor.setKeepAliveSeconds(60);
//线程名字前缀
executor.setThreadNamePrefix("MyExecutor-");
//当pool已经到达max size的时候,如何处理新任务,CallerRunsPolicy,由调用者所在的线程执行
executor.setThreadNamePrefix("thread-task-service-");
executor.initialize();
return executor;
}
}
// 使用
myTaskAsyncPool.execute(() -> {
// todo...
});
2 时间转换
/**
* ----------------------------------------- SimpleDateFormat 线程不安全 --------------------------
*/
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH");
// String 转 data
Date date1 = simpleDateFormat.parse("2019-09-02 20");
Date date2 = simpleDateFormat.parse("2019-09-02 21");
System.out.println(simpleDateFormat.format(date1));
// 相差几小时
System.out.println((date2.getTime() - date1.getTime())/1000/3600);
// UTC 转 String(data)
Date date = new Date(date2.getTime());
String dareString = simpleDateFormat.format(date);
System.out.println(dareString);
/**
* ---------------------------------- LocalDateTime 线程安全--------------------------------
* ---------------------String----TimeStamp----LocalDataTime----LocalData------------------
*/
public static LocalDateTime stringToLocalDateTime(String dateString, String pattern){
return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(pattern));
}
public static LocalDate stringToLocalDate(String dateString, String pattern){
return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(pattern));
}
public static long stringToTimeStamp(String dateString,String pattern){
if(pattern.contains("HH")){
return localDateTimeToTimeStamp(stringToLocalDateTime(dateString,pattern));
}
return localDateToTimeStamp(stringToLocalDate(dateString,pattern));
}
public static String localDateTimeToString(LocalDateTime time,String pattern){
return DateTimeFormatter.ofPattern(pattern).format(time);
}
public static long localDateTimeToTimeStamp(LocalDateTime time){
return time.toEpochSecond(ZoneOffset.of("+8"));
}
public static long localDateToTimeStamp(LocalDate time){
return time.atStartOfDay().toEpochSecond(ZoneOffset.of("+8"));
}
public static String localDateToString(LocalDate time,String pattern){
return DateTimeFormatter.ofPattern(pattern).format(time);
}
public static LocalDateTime timeStampToLocalDateTime(long timeStamp){
return LocalDateTime.ofEpochSecond(timeStamp,0,ZoneOffset.ofHours(8));
}
public static LocalDate timeStampToLocalDate(long timeStamp){
return Instant.ofEpochSecond(timeStamp).atOffset(ZoneOffset.of("+8")).toLocalDate();
}
public static String timeStampToString(long timeStamp,String pattern){
return localDateTimeToString(timeStampToLocalDateTime(timeStamp),pattern);
}
3 Double 取消科学计数法
double d = 112451254012.12485;
NumberFormat nf = NumberFormat.getInstance();
//设置保留多少位小数
nf.setMaximumFractionDigits(20);
// 取消科学计数法
nf.setGroupingUsed(false);
//返回结果
System.out.println(nf.format(d));
4 Maven 项目打包
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.cug.Main</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<!--下面是为了使用 mvn package命令,如果不加则使用mvn assembly-->
<executions>
<execution>
<id>make-assemble</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
5 执行可执行程序
String path = System.getProperty("user.dir")+"\\main.exe";
@Test
public void test1() throws IOException {
BufferedReader bufferedReader;
Process proc = Runtime.getRuntime().exec(path);
// 获取子进程的错误流,并打印
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(proc.getOutputStream());
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
}
@Test
public void test2() throws IOException {
Process p = new ProcessBuilder().command(path,"--url","http://localhost:8889").start();
InputStream i = p.getInputStream();
Scanner scanner = new Scanner(i);
while (scanner.hasNextLine()){
System.out.println(scanner.nextLine());
}
}
6 扫描线填充算法
package com.cug.web;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collections;
public class FillTest extends JFrame {
private ArrayList<Edge> edgeTable = new ArrayList<>();
private int getYmin() {
int yMin = edgeTable.get(0).y1;
for (Edge edge : edgeTable) {
if (edge.y1 < yMin)
yMin = edge.y1;
}
return yMin;
}
private int getYmax() {
int yMax = edgeTable.get(0).y1;
for (Edge edge : edgeTable) {
if (edge.y1 > yMax)
yMax = edge.y1;
}
return yMax;
}
private boolean isActive(Edge edge, int currentY) {
return edge.y1 < currentY && currentY <= edge.y2 || edge.y1 >= currentY && currentY > edge.y2;
}
private void updateActiveEdges(ArrayList<Edge> activeEdges, int y) {
for (Edge edge : edgeTable) {
if (isActive(edge, y)) {
if (!activeEdges.contains(edge)) {
activeEdges.add(edge);
}
} else {
activeEdges.remove(edge);
}
}
}
private void findIntersections(ArrayList<Integer> intersections, ArrayList<Edge> activeEdges, int currentY) {
intersections.clear();
for (Edge edge : activeEdges) {
int x = edge.x1 + ((currentY - edge.y1) * (edge.dx)) / (edge.dy);
intersections.add(x);
}
}
public void fill() {
ArrayList<Edge> activeEdges = new ArrayList(10);
ArrayList<Integer> intersections = new ArrayList(20);
Graphics g = getGraphics();
g.setColor(Color.red);
// x1,y1,x2,y2
edgeTable.add(new Edge(100, 100, 100, 600));
edgeTable.add(new Edge(100, 600,500,400));
edgeTable.add(new Edge(500,400, 100, 100));
int yMin = getYmin();
int yMax = getYmax();
for (int y = yMin; y < yMax; y++) {
updateActiveEdges(activeEdges, y);
findIntersections(intersections, activeEdges, y);
Collections.sort(intersections);
for (int i = 0; i < intersections.size(); i += 2) {
int x1 = intersections.get(i);
if (i + 1 >= intersections.size()){
break;
}
int x2 = intersections.get(i + 1);
g.drawLine(x1, y, x2, y);
}
}
}
public static void main(String[] args) {
FillTest s = new FillTest();
s.setSize(800, 800);
s.setVisible(true);
s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
s.fill();
}
}
class Edge {
int x1, y1, x2, y2, dx, dy;
Edge(int x1, int y1, int x2, int y2) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.dx = x2 - x1;
this.dy = y2 - y1;
}
}
7 JDK动态代理(只能代理实现了接口的类)
import org.junit.jupiter.api.Test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyTest {
interface SmsService {
void send(String message,String msg);
}
static class SmsServiceImpl implements SmsService {
public void send(String message,String msg) {
System.out.println("send message:" + message + "---" + msg);
}
}
static class DebugInvocationHandler implements InvocationHandler {
/**
* 代理类中的真实对象
*/
private final Object target;
public DebugInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
// 调用方法之前,添加自己的操作
System.out.println("before method " + method.getName());
Object result = method.invoke(target, args);
// 调用方法之后,添加自己的操作
System.out.println("after method " + method.getName());
return result;
}
}
@Test
void test1(){
SmsServiceImpl smsService1 = new SmsServiceImpl();
SmsService smsService = (SmsService) Proxy.newProxyInstance(
// 目标类的类加载
smsService1.getClass().getClassLoader(),
// 代理需要实现的接口,可指定多个
smsService1.getClass().getInterfaces(),
new DebugInvocationHandler(smsService1));
smsService.send("java","test");
}
}
8 cglib 动态代理
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
public class ProxyCglibTest {
static class SmsService {
public void send(String message,String msg) {
System.out.println("send message:" + message + "---" + msg);
}
}
/**
* 自定义MethodInterceptor
*/
static class DebugMethodInterceptor implements MethodInterceptor {
/**
* @param o 代理对象(增强的对象)
* @param method 被拦截的方法(需要增强的方法)
* @param args 方法入参
* @param methodProxy 用于调用原始方法
*/
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//调用方法之前,我们可以添加自己的操作
System.out.println("before method " + method.getName());
Object object = methodProxy.invokeSuper(o, args);
//调用方法之后,我们同样可以添加自己的操作
System.out.println("after method " + method.getName());
return object;
}
}
@Test
void test1(){
Class<SmsService> smsServiceClass = SmsService.class;
// 创建动态代理增强类
Enhancer enhancer = new Enhancer();
// 设置类加载器
enhancer.setClassLoader(smsServiceClass.getClassLoader());
// 设置被代理类
enhancer.setSuperclass(smsServiceClass);
// 设置方法拦截器
enhancer.setCallback(new DebugMethodInterceptor());
// 创建代理类
SmsService smsService = (SmsService) enhancer.create();
smsService.send("java","test");
}
}
9 反射
public class TargetObject {
private String value;
public TargetObject() {
value = "targetObject";
}
public void publicMethod(String s) {
System.out.println("publicMethod " + s);
}
private void privateMethod() {
System.out.println("privateMethod " + value);
}
}
public class Main {
public static void main(String[] args) throws Exception {
/**
* 获取 TargetObject 类的 Class 对象并且创建 TargetObject 类实例
*/
Class<?> targetClass = Class.forName("com.cug.TargetObject");
TargetObject targetObject = (TargetObject) targetClass.newInstance();
/**
* 获取 TargetObject 类中定义的所有方法
*/
Method[] methods = targetClass.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
/**
* 获取指定方法并调用
*/
Method publicMethod = targetClass.getDeclaredMethod("publicMethod",String.class);
publicMethod.invoke(targetObject, "targetObject");
/**
* 获取指定参数并对参数进行修改
*/
Field field = targetClass.getDeclaredField("value");
//为了对类中的参数进行修改我们取消安全检查
field.setAccessible(true);
field.set(targetObject, "modify");
/**
* 调用 private 方法
*/
Method privateMethod = targetClass.getDeclaredMethod("privateMethod");
//调用 private 方法,取消安全检查
privateMethod.setAccessible(true);
privateMethod.invoke(targetObject);
}
}
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());
}
}