Home > Java > javaTutorial > body text

Anonymous inner class for multithreading

高洛峰
Release: 2016-12-15 13:29:08
Original
1313 people have browsed it

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();
    }
}
Copy after login


For more articles related to multi-threaded anonymous internal classes, please pay attention to the PHP Chinese website!



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template