java 运行多线程轮询时,外部停止轮询

1,先建一个Map

/**
     * 创建一个Map用于存放线程id对象集合,主要是用于到达岗亭之后扫码付费,如果人工收费就需要关闭线程,key是停车记录Id,
     */
	public static Map MAPTHREAD = new HashMap();

2.建一个线程类继承Runnable

/**
 * 轮询查询网上支付结果
 * @author Administrator
 *
 */
@Component
public class PollingSearch implements Runnable{
    private String flag;
    
    private ParkingRecord parkingRecord;
    
//    @Autowired
//    private OnlinePaymentService onlinePaymentService;
    
    //@Autowired
    //private CameraLogic cameraLogic;
    
    @Override
    public void run() {
        try {
            CameraLogic cameraLogic =  (CameraLogic) SpringUtil.getObject("cameraLogic");
            OnlinePaymentService onlinePaymentService = (OnlinePaymentService) SpringUtil.getObject("onlinePaymentServiceImpl");
            while(CommonUtil.MAPTHREAD.get(flag).equals("true")) {
             
                Thread.sleep(5000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void setFlag(String flag) {
        this.flag = flag;
    }

    public ParkingRecord getParkingRecord() {
        return parkingRecord;
    }

    public void setParkingRecord(ParkingRecord parkingRecord) {
        this.parkingRecord = parkingRecord;
    }

    public String getFlag() {
        return flag;
    }

spring容器中无法自动注入,所以用这两句代码获取,springUtil可参考我的另一篇文章 spring ioc容器管理

            CameraLogic cameraLogic =  (CameraLogic) SpringUtil.getObject("cameraLogic");
            OnlinePaymentService onlinePaymentService = (OnlinePaymentService) SpringUtil.getObject("onlinePaymentServiceImpl");

重要的代码在这

while(CommonUtil.MAPTHREAD.get(flag).equals("true")) {

上面代码在根据map中判断了是否执行轮询,当为true时才执行

下面开启线程

		    final String parkRecordId = oldRecord.getId();
		    final ParkingRecord parkingRecord = oldRecord;
            //将账单id放进map中,为了等待支付完成时可以根据停车记录id找到该账单后删除
            CommonUtil.PAYMENTRECORDMAP.put(parkRecordId, paymentRecord.getId());
            CommonUtil.MAPTHREAD.put(parkRecordId, "true");
            PollingSearch pollingSearch = new PollingSearch();
            pollingSearch.setParkingRecord(parkingRecord);
            pollingSearch.setFlag(parkRecordId);
            Thread thread = new Thread(pollingSearch);
            thread.start();

在需要关闭线程的时候

		                final String parkingRecordId = parkingRecord.getId();
		                CommonUtil.MAPTHREAD.put(parkingRecordId,"false");
		                CommonUtil.MAPTHREAD.remove(parkingRecordId);

这样子就可以给各个线程手动关闭了

初学者,不喜勿怪 排版懒得排了

你可能感兴趣的:(学习笔记)