1 生成Thread对象
1.1 继承java.lang.Thread类
使用new字符新建Thread对象。参考下面的实现代码
/*
* 继承Thread类
* 创建Thread对象
*
*/
public class Extendsthread extends Thread {
private String name;
public Extendsthread(String name) {
this.name = name;
}
public void run() {
for( int i=0; i<10; i++ ){
System.out.println(this.name);
}
}
public static void main(String[] args) {
Thread t1 = new Extendsthread("线程1");
Thread t2 = new Extendsthread("线程2");
t1.start();
t2.start();
}
}
1.2 实现java.lang.Runnable接口
调用Thread的构造方法来创建Thread对象。
Thread(Runnable target)
/*
* 实现Runnble类
* 创建Thread对象
*
*/
public class ImpRunnable implements Runnable {
private String name;
public ImpRunnable(String name) {
this.name = name;
}
public void run() {
for( int i=0; i<10; i++ ){
System.out.println(this.name);
}
}
public static void main(String[] args) {
ImpRunnable impRunnable1 = new ImpRunnable("线程1");
ImpRunnable impRunnable2 = new ImpRunnable("线程2");
Thread t1 = new Thread( impRunnable1 );
Thread t2 = new Thread( impRunnable2 );
t1.start();
t2.start();
}
}
2 启动线程
调用Thread对象的start()方法。
在调用start()方法之前:线程处于新状态中,只是一个Thread对象,而不是线程。
在调用start()方法之后:发生了一系列复杂的事情
启动新的执行线程(具有新的调用栈);
该线程从新状态转移到可运行状态;
当该线程获得机会执行时,其目标run()方法将运行。