安卓中实现异步任务(4)——使用线程池实现
问题背景
上篇文章大致介绍了几种安卓汇总实现异步任务的方法,讲得比较简要,有朋友问到具体的实现方式,现在开始分列几篇文章详细介绍这几种异步的具体实现。这篇讲得是基于线程池实现,持续更新。
实现demo
(1)实现我们的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolUtil {
private static int fixNum = 6;
private static int maxNum = 8;
private static ExecutorService fixedThreadPool = new ThreadPoolExecutor(fixNum, maxNum,
0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());;
public static void executeRunnableByFixedPool(Runnable runnable) {
fixedThreadPool.execute(runnable);
}
}
(2)新建我们的activity,对应layout布局如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activity.HandlerThreadActivity">
<Button
android:id="@+id/btn1"
android:text="启动子线程"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>
(2)对应我们activity的代码如下:
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import com.alibaba.android.arouter.facade.annotation.Route;
public class HandlerThreadActivity extends AbstractSubActivity {
private static final String TAG = "HandlerThreadActivity";
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thread);
button = findViewById(R.id.btn1);
Thread.currentThread().setName("主线程");
Log.d(TAG, "主线程当前线程名为" + Thread.currentThread().getId()
+ " " + Thread.currentThread().getName());
HandlerThread handlerThread = new HandlerThread("子线程");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper(), msg -> {
if (msg.what == 1) {
Log.d(TAG, "handlerThread当前线程名为:" + Thread.currentThread().getId()
+ " " + Thread.currentThread().getName());
}
return true;
});
button.setOnClickListener(v -> {
handler.sendEmptyMessage(1);
ThreadPoolUtil.executeRunnableByFixedPool(() -> {
Log.d(TAG, "executeRunnableByFixedPool:" + Thread.currentThread().getId()
+ " " + Thread.currentThread().getName());
});
});
}
}
执行结果如下:
关键代码分析
持续更新。。。
标签:异步,Thread,currentThread,util,线程,安卓中,import,android From: https://blog.51cto.com/baorant24/5786154