java线程写法

来源:互联网 发布:皮带什么牌子好 知乎 编辑:程序博客网 时间:2024/04/29 05:29
   //线程创建方式1
        Thread thread=new Thread(){ 
            public void run() { 
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) { 
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread());
                }
            }
        };
        thread.start();
        
        //线程创建方式2
        Thread thread2=new Thread(new Runnable(){
            public void run() { 
                while(true){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) { 
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread());
                }
            }
        });
        
        thread2.start();
        
        //main程序
        while(true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) { 
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread());

        }



-------------------------------------------------------------------------------------------------

        //混合
        new Thread(new Runnable(){
            public void run() {
                System.out.println("Override runnable run!");
            }
        }){ 
            public void run() {
                //super.run();
                System.out.println("Override Thread run!");
            }
        }.start();

执行结果Override Thread run!

如果加上super.run();结果为:

Override runnable run!
Override Thread run!

0 0
原创粉丝点击