Android 队列执行demo
package com.myd.myloop;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.blankj.utilcode.util.ThreadUtils;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
public class MainActivity extends AppCompatActivity {
private Queue<Integer> loopDatas = new ConcurrentLinkedQueue<>();//队列
private int anInt = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addButton = findViewById(R.id.add);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
anInt++;
loopDatas.offer(anInt); //添加数据
}
}).start();
}
});
//开启队列监听,队列加入数据就会执行
startLoopListener();
}
public void startLoopListener(){
ThreadUtils.getIoPool().execute(new Runnable() {
@Override
public void run() {
try {
while (true){
if (loopDatas.size() > 0){
Integer value = loopDatas.poll();
if (value != null){
System.out.println("执行队列-读取到数据="+value);
}
Thread.sleep(1000);//队列执行间隔
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
}
}
本文标题:Android 队列执行demo
本文链接:https://www.haomeiwen.com/subject/bbvcmltx.html
网友评论