線程是CPU分配的最小單元
在Android 中有兩種實(shí)現(xiàn)線程的方法:
- 擴(kuò)展java.lang.Thread類(lèi)
- 實(shí)現(xiàn)Runnable接口
Thread 類(lèi)代表線程類(lèi),是Runnable的子類(lèi)计济,它有兩個(gè)最主要的方法:
- run()包含線程運(yùn)行時(shí)衷咽,要執(zhí)行的代碼屡拨;
- start用于啟動(dòng)線程
Runnables是一個(gè)接口壕探,實(shí)現(xiàn)它的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() {
//訪問(wèn)網(wǎng)絡(luò)
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()
}
第三種啟動(dòng)線程的方式
通過(guò)handler啟動(dòng)
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);//自己發(fā)送給自己怖侦,每隔3秒發(fā)一次
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandle.post(mRunnable);//第一此 虱肄,啟動(dòng)Runnable
}
@Override
protected void onDestroy() {
mHandle.removeCallbacks(mRunnable);//銷(xiāo)毀線程
super.onDestroy();
}
}