通过实现 Runnable 接口
实例
public class TestThread {
public static void main(String[] args) {
RunnableDemo r1 = new RunnableDemo("Thread-1");
r1.start();
RunnableDemo r2 = new RunnableDemo("Thread-2");
r2.start();
RunnableDemo r3 = new RunnableDemo("Thread-3");
r3.start();
}
}
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo(String threadName) {
this.threadName = threadName;
System.out.println("Create " + threadName);
}
public void run() {
System.out.println("Run " + threadName);
try {
for (int i = 0; i < 4; i++) {
System.out.println("Thread " + threadName + " " + i);
Thread.sleep(30);
}
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Exception " + threadName);
}
System.out.println("Exit " + threadName);
}
public void start() {
System.out.println("Start " + threadName);
if (t == null) {
t = new Thread(this, threadName);
}
t.start();
}
}
Thread其中一个常用的构造方法
Thread(Runnable threadOb,String threadName);//threadOb是一个实现Runnable接口的类的实例;threadName是新线程的名字。
文章仅作为个人学习整理