1,继承自Thread类
public class Thread1 extends Thread{
@Override
public void run() {
System.out.println(this.getName());
}
public static void main(String[] args) {
Thread1 t = new Thread1();
t.start();
}
}
2,实现Runnable接口(使用Runnable接口更加灵活)
public class T {
private String name;
public T(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
public class Thread2 extends T implements Runnable {
public Thread2(String name){
super(name);
}
public void run() {
System.out.println(this.getName());
}
public static void main(String[] args) {
Thread1 t = new Thread1("thread1");
t.start();
}
}
Thread类本身也是Runnable接口的一个具体实现:
public class Thread implements Runnable { ....
}
在启动线程时,一定不要使用Thread.run(),这将变成方法调用而不是启动线程,虽然Thread.start()本质上还是调用线程的run()方法
/**
* Causes this thread to begin execution; the Java Virtual Machine
* calls the <code>run</code> method of this thread.
* <p>
* The result is that two threads are running concurrently: the
* current thread (which returns from the call to the
* <code>start</code> method) and the other thread (which executes its
* <code>run</code> method).
* <p>
* It is never legal to start a thread more than once.
* In particular, a thread may not be restarted once it has completed
* execution.
*
* @exception IllegalThreadStateException if the thread was already
* started.
* @see java.lang.Thread#run()
* @see java.lang.Thread#stop()
*/
public synchronized void start() {
if (started)
throw new IllegalThreadStateException();
started = true;
group.add(this);
start0();
}