当前位置: 代码迷 >> Android >> android handler操作线程的两种形式
  详细解决方案

android handler操作线程的两种形式

热度:44   发布时间:2016-05-01 19:48:08.0
android handler操作线程的两种方式
实现了Runnable的线程类:
public class MyRunnable implements Runnable
{

@Override
public void run()
{
  // TODO Auto-generated method stub
   System.out.println("Runnable---The Thread is running");
         System.out.println("Runnable---The Thread id is :"+ Thread.currentThread().getId()+"-"+Thread.currentThread().getName());
         try
  {
   Thread.sleep(6000);
  } catch (InterruptedException e)
  {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

}

}
1.在主线程(UI线程)中执行Runnable
public class HandlerdemoActivity extends Activity {
private Handler handler=new Handler();
private myrunnable runnable=new myrunnable();
        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler.post(runnable);
        System.out.println("Oncreate---The Thread id is :"+ Thread.currentThread().getId()+"-"+Thread.currentThread().getName());
        setContentView(R.layout.main);
    }
}
2.在非主线程(子线程)中执行Runnable
public class handlerdemo1 extends Activity
{
private Handler handler = null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
HandlerThread handlerThread = new HandlerThread("myHandlerThread");
        handlerThread.start();

        handler = new Handler(handlerThread.getLooper());//获取Looper对象的引用

        handler.post(new MyRunnable());

        System.out.println("Oncreate---The Thread id is :"+ Thread.currentThread().getId()+"-"+Thread.currentThread().getName());
        setContentView(R.layout.main);

}
}
  相关解决方案