单线程循环获取数据

单线程获取数据,如果有数据就循环执行,如果获取不到数据执行10次退出

public class JikaoUtils {
    public static ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
}

处理业务逻辑的线程

public class GetScoreSingletonThread extends Thread {
    private Integer rootOrgId;
    private Map authHeader ;
    /**
     * 是否正在处理
     */
    private AtomicBoolean running ;


    public  GetScoreSingletonThread(Map map,Integer _rootOrgId, NetSignupService _signupService, Long yearId, AtomicBoolean _running)
    {    super();
        this.authHeader = map;
        this.rootOrgId = _rootOrgId;
        this.signupService = _signupService;
        this.yearId = yearId;
        this.running = _running;

    }
    public void run() {
        if (!running.compareAndSet(false, true)) {
            return;
        }
        int count = 0;
        while (true) {
            try {
                if (!execute()) {             
                    break;
                }
            } catch (Exception e) {

                count++;
            }
            
            // 10次异常后线程退出
            if (10 < count) {
                break;
            }
        }
        if (!running.compareAndSet(true, false)) {
            throw new RuntimeException("status exception");
        }
    }
    private boolean execute() {
      //程序正常      .......
      return true;
     程序异常
    return false; 
    }
   }

action调用

public class GetScoreFromJikaoAction extends TheolAction {
    /**
     * 是否正在处理
     */
    private static AtomicBoolean running = new AtomicBoolean(false);

    protected ActionForward actionPerformed(
            ActionMapping actionMapping,
            ActionForm actionForm,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {

   
        String scoreTag = request.getParameter("scoreTag");
        if ("1".equals(scoreTag)) {

            if (running.get()) {
                return null;
            }
          
            JikaoUtils.singleThreadExecutor.execute(new GetScoreSingletonThread(header, Integer.parseInt(jikaoRootOrgId),signupService, yearId,running));
      
        }
        return  null;
    }
}

你可能感兴趣的:(线程)