package thread;
/**
* @author flyfire
* @date:2011-10-27 下午07:37:38
* @introduce :以匿名内部类的方式创建线程
*
*/
public class internalthread {
//程序主函数
public static void main(string args[]){
for(int i=0;i<10;i++){
internalthread it=new internalthread();
it.startthread(i);
}
}
//该方法会启动一个匿名线程
public void startthread(int i){
//要传入匿名线程内使用的参数必须定义为final型
final int id=i;
runnable runnable=new runnable(){
public void run(){
while(true){
/*
* thread.sleep(long time)方法只是让线程暂停,而非退出
* 休眠时间结束后,vm会将线程重新调为运行状态。当线程在
* sleep状态时,如果vm或其他线程强行终止这个线程,sleep
* 方法会抛出interruptedexception异常,这叫做线程中断异常
* 所以,在调用sleep方法时,需要处理或抛出这个异常
*/
try{
system.out.println(id+"号线程已启动");
thread.sleep(10000);
}catch(exception e){
e.printstacktrace();
}
}
}
};
thread thread=new thread(runnable);
thread.start();
}
}
更多多线程之匿名内部类。