public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private boolean mToggle = true;
private DealEventThread mDealEventThread;
private volatile int cnt = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMyPostQueue = new MyPostQueue();
executorService = Executors.newCachedThreadPool();
}
public void startMyLogger(View view) {
mToggle = true;
new Thread(new AddEventThread()).start();
}
public void stopMyLooper(View view) {
mToggle = false;
}
// 事件队列
private MyPostQueue mMyPostQueue;
class AddEventThread implements Runnable {
@Override
public void run() {
while (mToggle){
MyPost myPost = MyPost.obtainMyPost(cnt++ + "");
synchronized (MainActivity.this) {
mMyPostQueue.enqueue(myPost);
Log.d(TAG, "run: add event" + myPost.mMsg);
if (!executorRunning) {
executorRunning = true;
if (mDealEventThread==null) {
mDealEventThread = new DealEventThread();
}
executorService.execute(mDealEventThread);
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
private static ExecutorService executorService;
private volatile boolean executorRunning;
class DealEventThread implements Runnable {
@Override
public void run() {
try {
while (true) {
MyPost pendingPost = mMyPostQueue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = mMyPostQueue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
Thread.sleep(1000);
// deal
Log.d(TAG, "run: deal event:" + pendingPost.mMsg);
//...
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executorRunning = false;
}
}
}
}
EventBus肢解-事件队列
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- 前言 说起Eventbus,相信不少同学都已经使用过。之前一直听别人提起,但是我一直没有使用过。前段时间在做一个I...
- 前言 学过Android的同学应该都用过的一个框架->EventBus. 在我们需要的地方设置一个监听,在另外一段...
- 1. 概述 EventBus是一个Android端优化的publish/subscribe消息总线,简化了应用程序...