Android线程操作类(暂停、重新开启、停止)

场景:
在程序中如果需要在后台长时间做一件事情,比如联网获取数据等操作,就要用到线程。
但为了提高用户体验,有以下几点需要注意:
1、程序可见时线程开始运行;
2、程序不可见时线程暂停;
3、程序退出时停止线程;

以下根据我自己的程序提出一个公用的代码,大家可以把自己的业务逻辑套进去:



public class NetUtil2 extends Thread {

//NewsBrief为新闻实体类;
private List<NewsBrief> loopList = new ArrayList<NewsBrief>();

private boolean isClose = false;

//IObtainData为一个接口,因为很多程序在用,因此拿Map存储;
private Map<Integer, IObtainData> obtainMap = new HashMap<Integer, IObtainData>();
private int currentPage = 0;
private boolean isPause = false;

private NetUtil2() {
}

private static NetUtil2 single = null;

public synchronized static NetUtil2 getInstance() {
if (single == null) {
single = new NetUtil2();
}
return single;
}

public synchronized void addNewsBrief(NewsBrief newsBrief) {
loopList.add(newsBrief);
//有数据要处理时唤醒线程
this.notify();
}

public void setObtainDataListener(int channelId, IObtainData iod) {
//添加回调
if (!obtainMap.containsKey(channelId)) {
obtainMap.put(channelId, iod);
}
}

public void setCurrentPage(int page) {
currentPage = page;
}

/**
* 暂停线程
*/
public synchronized void onThreadPause() {
isPause = true;
}

/**
* 线程等待,不提供给外部调用
*/
private void onThreadWait() {
try {
synchronized (this) {
this.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 线程继续运行
*/
public synchronized void onThreadResume() {
isPause = false;
this.notify();
}

/**
* 关闭线程
*/
public synchronized void closeThread() {
try {
notify();
setClose(true);
interrupt();
} catch (Exception e) {
e.printStackTrace();
}
}

public boolean isClose() {
return isClose;
}

public void setClose(boolean isClose) {
this.isClose = isClose;
}

@Override
public void run() {
while (!isClose && !isInterrupted()) {
if (loopList.size() > 0 && !isPause) {
int index = 0;
NewsBrief newsBrief = null;
// 当前页面优先加载
for (int i = 0; i < loopList.size(); i++) {
if (loopList.get(i).getChannelId() == currentPage) {
newsBrief = loopList.get(i);
index = i;
break;
}
}
if (null == newsBrief) {
newsBrief = loopList.get(0);
}
String reslut = getNewsContent(newsBrief);

if (!"-1".equals(reslut)) {
// 获取成功,更新
if (obtainMap.containsKey(newsBrief.getChannelId())) {
obtainMap.get(newsBrief.getChannelId())
.updateNewsBrief(newsBrief);
}
synchronized (loopList) {
loopList.remove(index);
}
} else {
//获取失败,移至队尾
synchronized (loopList) {
NewsBrief nb = loopList.remove(index);
loopList.add(nb);
}
}
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
onThreadWait();
}
}
}
}


注意:
线程的暂停用isPause控制,说白了其实就是不让线程进入wait状态;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值