线程是CPU分配的最小单元
在Android 中有两种实现线程的方法:
- 扩展java.lang.Thread类
- 实现Runnable接口
Thread 类代表线程类,是Runnable的子类,它有两个最主要的方法:
- run()包含线程运行时,要执行的代码;
- start用于启动线程
Runnables是一个接口,实现它的run方法:
public class ToolsJava {
String TAG = "ToolsJava";
ToolsThread t1 = new ToolsThread();
ToolsRunnable t2 = new ToolsRunnable();
public void ii() {
t1.start();
new Thread(t2).start();
}
}
public class ToolsThread extends Thread {
String TAG = "ToolsThread";
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Log.e(TAG, "ToolsThread i is : " + i);
}
}
}
public class ToolsRunnable implements Runnable {
String TAG = "ToolsRunnable";
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Log.e(TAG, "ToolsRunnable i is : " + i);
}
}
}
kotlin代码:
package com.lisxhs.kuaiyue.Test
import android.util.Log
/**
* Created by Administrator on 2017/7/26.
*/
class ktThread : Thread {
val TAG: String = "KTThread"
constructor() : super()
override fun run() {
//访问网络
for (i in 1..100) {
Log.e(TAG, "KTThread i is : " + i)
}
Log.e(TAG, "Thread name is " + this.name + " Therad id is " + this.id)
}
override fun start() {
super.start()
}
}
class ktRunnable() : Runnable {
val TAG: String = "ktRunnable"
override fun run() {
for (i in 100..1000) {
Log.e(TAG, "ktRunnable i is : " + i)
}
Log.e(TAG, "Thread name is " + Thread.currentThread().name + " Therad id is " + Thread.currentThread().id)
}
}
class Main {
var t2 = ktRunnable()
val t1 = ktThread().start()
val t3 = Thread(t2).start()
}
第三种启动线程的方式
通过handler启动
package com.hyphenate.easeuisimpledemo;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import com.hyphenate.easeui.ui.EaseBaseActivity;
public class MainActivity extends EaseBaseActivity {
private int count = 0;
private String TAG = "MainActivity";
private Handler mHandle = new Handler();
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
Log.e(TAG, Thread.currentThread().getName() + Thread.currentThread().getId());
Log.e(TAG, "count >>>" + count);
count++;
mHandle.postDelayed(mRunnable, 3000);//自己发送给自己,每隔3秒发一次
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandle.post(mRunnable);//第一此 ,启动Runnable
}
@Override
protected void onDestroy() {
mHandle.removeCallbacks(mRunnable);//销毁线程
super.onDestroy();
}
}