在AndroidStudio中如果要操作一些耗时的操作需要使用多线程来进行计算,下面列出一些常用的实现方法:
1. 继承Thread类
1.1 新建一个java类,并使其继承Thread
public class Script_Thread extends Thread
{
@Override
public void run()
{
Log.i(Tag, "线程已运行完毕!");
}
}
1.2 在MainActivity中调用
private void StartThread()
{
Script_Thread thr= new Script_Thread();
thr.start();
Log.i("启动线程", "已启动线程!");
}
2. 匿名Thread类,使用Runnable接口
2.1 可以直接写在MainActivity中
new Thread(new Runnable()
{
@Override
public void run()
{
Log.i("启动线程", "已启动线程!");
}
}).start();
3. 实现Runnable接口
3.1 新建一个java类,并使其实现Runnable
public class Script_MyRunnable implements Runnable
{
@Override
public void run()
{
Log.i("启动线程", "已通过实现Runnable启动线程");
}
}
3.2 在MainActivity中调用
private void StartThread()
{
Thread thr= new Thread(new Script_MyRunnable());
thr.start();
}