public class MainActivity extends AppCompatActivity { ImageView mImageView; private ExecutorService mThreadPool; private LinkedList<Runnable> mTaskQueue; private Thread mPoolThread; private Handler mPoolThreadHandler; static int countBuild = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTaskQueue = new LinkedList<>(); mThreadPool = Executors.newFixedThreadPool(10);//创建10个线程 for (int i = 0; i < 10; i++) { mTaskQueue.add(buildTask()); } // 后台轮询线程 mPoolThread = new Thread() { @Override public void run() { Looper.prepare(); mPoolThreadHandler = new Handler() { @Override public void handleMessage(Message msg) { // 线程池去取出一个任务进行执行 mThreadPool.execute(mTaskQueue.removeFirst()); } }; Looper.loop(); } ; }; mPoolThread.start(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } for (int j = 0; j < 10; j++) { mPoolThreadHandler.sendEmptyMessage(0x110); } } private Runnable buildTask() { return new Runnable() { @Override public void run() { countBuild++; Log.d("snow", "运行线程:" + countBuild); } }; } }
Android笔记->Executors应用学习
最新推荐文章于 2024-08-12 04:05:39 发布