khi tạo Thread, chương trình sẽ chia ra để hành động, hành động được đưa vào thread được thực hiện độc lập và cập nhật thuộc tính các đối tượng mà nó dùng tới. Khi không dùng Thread, chương trình hiểu là, ừ cứ làm việc này trước rồi tổng kết kết quả luôn 1 lượt.
Thread là 1 class mà nó thực thi Runnable, và có hàm run mặc định trong đó. khi có 1 class thực thi Runnable và có hàm run trong đó, thì nó là 1 Thread, ví du:
class a implements Runnable{
public void run(){..}
}
, ta có thể tạo 1 Thread từ nó:
Thread t= new Thread(new a());
và muốn cho thread khởi chạy ta dùng hàm start(), t.start(); khi đó hàm run() sẽ được thực thi.
*Ví dụ:
package mobile;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;
/**
* @author HOLYEYED
*/
public class Midlet extends MIDlet implements Runnable, CommandListener {
Command th = new Command("thread", Command.OK, 1);
Command nth = new Command("no thread", Command.OK, 2);
Form f = new Form("ket qua");
public void startApp() {
f.addCommand(th);
f.addCommand(nth);
f.setCommandListener(this);
Display.getDisplay(this).setCurrent(f);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == th) {
new Thread(this).start();
} else {
app();
}
}
public void app() {
long x = System.currentTimeMillis();
int c = 0;
while (x > System.currentTimeMillis() - 7000) {
if ((System.currentTimeMillis() - x) % 1000 == 0) {
f.append("" + c++);
}
}
}
public void run() {
app();
}
}
Source:
Midlet.java (1.41 KB)
Nguồn: Holyeyed