• Androidの多线程之HandlerThread


    1.Handler.post(Runnable),必须要有有Looper。

     1 package com.bvin.study.thread;
     2 
     3 import android.app.Activity;
     4 import android.os.Bundle;
     5 import android.os.Handler;
     6 import android.os.HandlerThread;
     7 import android.os.Looper;
     8 import android.os.Message;
     9 import android.util.Log;
    10 
    11 public class MainActivity extends Activity {
    12     /** Called when the activity is first created. */
    13     
    14     /*private Handler handler = new Handler(){
    15 
    16         @Override
    17         public void handleMessage(Message msg) {
    18             // TODO Auto-generated method stub
    19             super.handleMessage(msg);
    20             setTitle((String)msg.obj);
    21             
    22         }
    23         
    24         
    25         
    26     };*/
    27     private Handler handler = null;
    28     
    29     public int flag = 0;
    30     @Override
    31     public void onCreate(Bundle savedInstanceState) {
    32         super.onCreate(savedInstanceState);
    33         /*Handler+HandlerThread*/
    34         HandlerThread handerThread = new HandlerThread("myHanderThread");//建立HandlerThread
    35         handerThread.start();//运行HandlerThread(一定要开始才能获取Looper.否则得到是空值)
    36         Looper looper = handerThread.getLooper();//获取消息循环
    37         handler = new Handler(handerThread.getLooper());//建立带消息循环的Handler
    38         handler.post(new WorkRun());//执行线程
    39         
    40         /*Thread+Runnable*/
    41         /*Thread th = new Thread(new WorkRun());
    42         th.start();*/
    43         
    44         Log.e("ID:"+Thread.currentThread().getId(), "MainThread is running");
    45         setContentView(R.layout.main);
    46         
    47     }
    48     
    49     
    50     private class WorkRun implements Runnable{
    51 
    52         @Override
    53         public void run() {
    54             // TODO Auto-generated method stub
    55             
    56             Log.e("ID:"+Thread.currentThread().getId(), "WorkThread is running");
    57             
    58             try {
    59                 Thread.sleep(1000*6);
    60             } catch (InterruptedException e) {
    61                 // TODO Auto-generated catch block
    62                 e.printStackTrace();
    63             }
    64             
    65         }
    66         
    67         
    68         
    69     }
    70 }
  • 相关阅读:
    NLP(七):textCNN
    pandas(一):选取部分(行、列)写入到另一个文件
    (二) PCA的数学原理
    NLP(六):BiLSTM_Attention实现
    python(三):collection模块
    tensorflow(二十五):Tensorboard可视化
    推荐系统(二):基于pytorch的textdeepfm
    引用相关
    带缺省参数的重复声明
    运算符优先级
  • 原文地址:https://www.cnblogs.com/bvin/p/2665781.html
Copyright © 2020-2023  润新知