[color=darkred]实现了Runnable的线程类:[/color]
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();
}
}
}
[color=brown]1.在主线程(UI线程)中执行Runnable[/color]
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);
}
}
[color=brown]2.在非主线程(子线程)中执行Runnable[/color]
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);
}
}
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();
}
}
}
[color=brown]1.在主线程(UI线程)中执行Runnable[/color]
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);
}
}
[color=brown]2.在非主线程(子线程)中执行Runnable[/color]
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);
}
}