package com.product.admin.service;
|
|
|
import com.product.core.exception.BaseException;
|
import org.springframework.stereotype.Component;
|
|
import java.util.ArrayList;
|
import java.util.Collections;
|
import java.util.List;
|
|
/**
|
* @program: base-server-admin
|
* @description: 更新用户信息独立线程类
|
* @author: xu peng cheng
|
* @create: 2020-12-22 14:17
|
*/
|
@Component
|
public class ThreadUpdateUserInfoService {
|
|
protected List<Object[]> users = Collections.synchronizedList(new ArrayList<>());
|
|
protected UpdateUserThread updateUserThread;
|
|
protected static ThreadUpdateUserInfoService threadUpdateUserInfoService;
|
|
/**
|
* 回调方法接口
|
*/
|
public interface CallBack {
|
void method(Object... objects);
|
}
|
|
public synchronized void add(CallBack callBack, Object[] params) {
|
synchronized (users) {
|
users.add(new Object[]{callBack, params});
|
}
|
}
|
|
/**
|
* 获取当前类实例
|
*
|
* @return
|
*/
|
public static synchronized ThreadUpdateUserInfoService getInstance() {
|
if (threadUpdateUserInfoService == null) {
|
threadUpdateUserInfoService = new ThreadUpdateUserInfoService();
|
}
|
return threadUpdateUserInfoService;
|
}
|
|
/**
|
* 取出数据
|
*
|
* @return
|
*/
|
private synchronized List<Object[]> getUsers() {
|
List<Object[]> user = new ArrayList<>();
|
synchronized (users) {
|
user.addAll(users);
|
users.clear();//清除数据
|
}
|
return user;
|
}
|
|
/**
|
* 启动独立线程刷新用户信息
|
*/
|
public synchronized void start() {
|
if (updateUserThread == null || updateUserThread.getState() == Thread.State.TERMINATED) {
|
updateUserThread = new UpdateUserThread("update-user-info-thread");
|
updateUserThread.start();
|
}
|
}
|
|
/**
|
* 线程内部类
|
*/
|
class UpdateUserThread extends Thread {
|
|
public UpdateUserThread(String name) {
|
setName(name);
|
}
|
|
@Override
|
public void run() {
|
while (!isInterrupted()) {
|
List<Object[]> pop = getUsers();
|
try {
|
Thread.currentThread().sleep(3000);
|
if (pop.size() > 0) {
|
for (int i = 0; i < pop.size(); i++) {
|
try {
|
Object[] objects = pop.get(i);
|
CallBack callBack = (CallBack) objects[0];
|
Object[] params = (Object[]) objects[1];
|
//调用方法
|
callBack.method(params);
|
} catch (BaseException e) {
|
e.printStackTrace();
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
} else {
|
interrupt();
|
}
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
}
|
}
|