public class MyThread extends Thread{
//整个的构造函数就跑在主线程中
//仅仅在run方法中的程序才跑在MyThread的线程中。
public MyThread(){
print("MyThread Construct Before");
start();
print("MyThread Construct After");
}
@Override
public void run(){
int i = 0;
while(true){
i++;
if(i<3){
print("MyThread");
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
return;
}
}
}
//在哪里调用此函数,此函数就跑在哪个线程中
private void print(String tag){
System.out.println(tag+":"+Thread.currentThread().getId());
}
}
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Main:"+Thread.currentThread().getId());
MyThread m = new MyThread();
try {
m.join();//主线程挂起,直到线程m结束才恢复
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done");
}
}
//console output
Main:1
MyThread Construct Before:1
MyThread Construct After:1
MyThread:8
MyThread:8
Done