首页 > 编程语言 > 详细

Java多线程传统实现方法

时间:2015-03-23 23:59:46      阅读:527      评论:0      收藏:0      [点我收藏+]

Java多线程传统实现方法

Java多线程的传统实现方法有两种:一种是继承Thread类并重写其run方法;另一种是实现Runnable接口,实现其run方法。

/**
 * 多线程的传统实现方法
 *
 */
public class TraditionalThread {

    public static void main(String[] args) {

        /*
         * 方法1:覆盖父类Thread的run方法
         */
        Thread thread = new Thread() {

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("输出1:" + Thread.currentThread().getName());
                    System.out.println("输出2:" + this.getName());
                }
            }

        };
        thread.start();

        /*
         * 方法2:实现Runnable接口,实现其run方法
         */
        Thread thread2 = new Thread(new Runnable() {

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("输出1:" + Thread.currentThread().getName());
//                  System.out.println("输出2:" + this.getName());
                }
            }

        });
        thread2.start();

        /*
         * 3:二者同时存在时的调用规则
         * 
         * 首先找子类的run方法,
         * 若子类没有覆盖run方法,则找Runnable的run方法(参考jdk中Thread.run()的实现)
         * 因此本代码会执行子类覆盖的run方法
         */
        new Thread(new Runnable(){

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Runnable:" + Thread.currentThread().getName());
                }
            }

        }){

            @Override
            public void run() {
                while(true) {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread:" + Thread.currentThread().getName());
                }
            }

        }.start();
    }

}

Java多线程传统实现方法

原文:http://blog.csdn.net/kingzone_2008/article/details/44571181

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!