在 Java 语言中,我们可以通过下列两种方式来实现我们的 run 方法:
1、覆盖 java.lang.Thread 的 public void run() 方法。
public class SimpleThread extends Thread {
public SimpleThread(String str) {
super(str);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
}
}
System.out.println("DONE! " + getName());
}
}调用上面定义的线程:
public class TwoThreadsDemo {
public static void main(String[] args) {
new SimpleThread("Jamaica").start();
new SimpleThread("Fiji").start();
}
}
2、实现 java.lang.Runnable 接口:
import java.awt.Graphics;
import java.util.*;
import java.text.DateFormat;
import java.applet.Applet;
public class Clock extends Applet implements Runnable {
private Thread clockThread = null;
public void start() {
if (clockThread == null) {
clockThread = new Thread(this, "Clock");
clockThread.start();
}
}
public void run() {
Thread myThread = Thread.currentThread();
while (clockThread == myThread) {
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
public void paint(Graphics g) {
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
DateFormat dateFormatter = DateFormat.getTimeInstance();
g.drawString(dateFormatter.format(date), 5, 10);
}
public void stop() {
clockThread = null;
}
}