循环里创建多条线程,怎么终止线程,防止内存溢出?

循环里创建多条线程,最后终止线程的方法

private Thread thumbImgThread; // 只用一个变量
public void notifyDataChanged(DeviceListModel deviceList) {
    cameraBriefInfoList.clear();
    if(deviceList == null){
        return;
    }
    cameraBriefInfoList = deviceList.getCameraBriefInfos().getCameraBriefInfoList();
    if(cameraBriefInfoList!=null && cameraBriefInfoList.size() > 0){
        videoList = new ArrayList<VideoListModel.RecordInfo>();
        for(int i=0;i< cameraBriefInfoList.size();i++){
            try {
                final int finalI = i;
                thumbImgThread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            doOkHttpResponse(cameraBriefInfoList.get(finalI).getName(),cameraBriefInfoList.get(finalI).getCode(),cameraBriefInfoList.get(finalI).getDomainCode());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
                thumbImgThread.start();
                showLoading();
            } catch (Exception e) {
                Toast.makeText(this, "截图操作异常", Toast.LENGTH_LONG).show();
            }
        }
    }
}

 

 

public void doOkHttpResponse(final String name,final String code, final String domainCode) throws JSONException {
    //请求参数
    String url = ApiRetrofit.BASE_SERVER_URL + "snapshot/manualsnapshot";
    String cameraCode = code+"#" + domainCode;
    JSONObject jsonData = new JSONObject();
    jsonData.put("cameraCode", cameraCode);
    RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonData.toString());
    OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
    clientBuilder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
    clientBuilder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());
    clientBuilder
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    Response response = chain.proceed(chain.request());
                    String cookie = response.header("Set-Cookie");
                    if (cookie != null && !cookie.isEmpty()) {
                        String[] data = cookie.split(";");
                        if (data.length >= 1)
                            SPUtils.put(App.app, Constants.KEY_COOKIE, data[0]);
                    }
                    return response;
                }
            })
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    String cookie = (String) SPUtils.get(App.app, Constants.KEY_COOKIE, "");
                    Request request = chain.request().newBuilder().addHeader("Cookie", cookie).build();
                    return chain.proceed(request);
                }
            })
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS);
    OkHttpClient client = clientBuilder.build();
    Request request = new Request.Builder().url(url).post(body).build();
    Call call = client.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            hideLoading();
            System.out.println("----------error----------");
        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onResponse(Call call, Response response)
                throws IOException {
            byte[] bytes = response.body().bytes();
            if (bytes.length < 1) {
                return;
            }
            InputStream input, input_copy;
            Bitmap bitmap;
            BitmapFactory.Options options = new BitmapFactory.Options();
            input = new ByteArrayInputStream(bytes);
            input_copy = new ByteArrayInputStream(bytes);
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(input, null, options);
            int width = options.outWidth;
            int height = options.outHeight;
            options.inJustDecodeBounds = false;
            options.inSampleSize = ImageUtil.calculateInSampleSize(options, 500);
            SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(input_copy, null, options));
            bitmap = (Bitmap) softRef.get();
            try {
                if (input != null) {
                    input.close();
                }
                if (input_copy != null) {
                    input_copy.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                bytes = null;
            }
            //Render ImageView
            final Bitmap finalBitmap = bitmap;
            if(bitmap!=null){
                VideoListModel.RecordInfo recordInfo = new VideoListModel.RecordInfo();
                recordInfo.setSnapShot(finalBitmap);
                recordInfo.setCode(code);
                recordInfo.setDomainCode(domainCode);
                recordInfo.setRecordFileName(name);
                videoList.add(recordInfo);
            }

            if(videoList!=null && videoList.size() > 0 && videoList.size()==cameraBriefInfoList.size()){ // 如果添加完毕
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(videoList!=null && videoList.size() > 0){
                            if(isFirstShow){
                                mVideoList.add(videoList.get(0)); // 只展现主画面,模拟场景
                            }else{
                                mVideoList = videoList;
                            }
                            binding.videoRecyclerview.setAdapter(mVideoMenuAdapter = new VideoMenuAdapter(mVideoList, MainActivity.this));
                            if (mVideoMenuAdapter != null) {
                                hideLoading();
                                mVideoMenuAdapter.notifyDataSetChanged();
                                if(!thumbImgThread.isInterrupted()){
                                    thumbImgThread.interrupt();
                                }
                            }
                        }
                    }
                });
            }else if(videoList==null || videoList.size() ==0){
                hideLoading();
            }
        }
    });
}

 

 

@Override
protected void onDestroy() {
    super.onDestroy();
    if(thumbImgThread!=null){
        thumbImgThread = null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值