抽象类和接口的区别如下:
①在类来继承抽象类时,只需实现部分具体方法和全部抽象方法,而实现接口则要实现里面的全部方法。
②在接口中无成员变量,而抽象类中可有成员变量。
在Java中引进接口主要是为了解决多继承的问题。
实现多线程主要继承 Thread 类和实现Runnable接口。
new Thread(new Runnable() {
public void run() {
...
});
}).start();
public MyThread() extends Thread{
public void run() {
...
}
}
还有几种线程用法:
private Handler guiThread;
private runnable updateTask = new Runnable () {
public void run() {
....
}
}
guiThread.removeCallbacks(updateTask);
guiThread.postDelayed(updateTask, delayMillis);
这样仍然是在主线程里。
guiThread.post(new R unnable() {
public void run() {
....
}
}
另一种:
private ExecutorService transThread = Executors.newSingleThreadExecutor();
TranslateTask translateTask = new TaskslateTask(
...
};
异常任务模型
1. 四步
onPreExcute(param...)
doInBackground(param...)
onProcessUpdate(progress...)
onPostExcute(param...)
2.四原则
只能在UI线程创建
只能在UI线程执行
四步函数不能显示调用
任务只运行一次,再次运行抛出异常
3.参数说明
AsyncTask的3个参数分别是 doInBackground的参数, doInBackground的返回类型(也是 onPostExecute的参数 ), onPostExecute的返回类型。
/**
* Async task for loading a single message outside of the UI thread
* Note: To support unit testing, a sentinel messageId of Long.MIN_VALUE prevents
* loading the message but leaves the activity open.
*/
private class LoadMessageTask extends AsyncTask<Void, Void, Message> {
private long mId;
private boolean mOkToFetch;
/**
* Special constructor to cache some local info
*/
public LoadMessageTask(long messageId, boolean okToFetch) {
mId = messageId;
mOkToFetch = okToFetch;
}
@Override
protected Message doInBackground(Void... params) {
if (mId == Long.MIN_VALUE) {
return null;
}
return Message.restoreMessageWithId(MessageView.this, mId);
}
@Override
protected void onPostExecute(Message message) {
/* doInBackground() may return null result (due to restoreMessageWithId())
* and in that situation we want to Activity.finish().
*
* OTOH we don't want to Activity.finish() for isCancelled() because this
* would introduce a surprise side-effect to task cancellation: every task
* cancelation would also result in finish().
*
* Right now LoadMesageTask is cancelled not only from onDestroy(),
* and it would be a bug to also finish() the activity in that situation.
*/
if (isCancelled()) {
return;
}
if (message == null) {
if (mId != Long.MIN_VALUE) {
finish();
}
return;
}
reloadUiFromMessage(message, mOkToFetch);
startPresenceCheck();
}
}
线程同步: