Java多线程(一)Java多线程传统实现方法

jopen 8年前

Java多线程(一)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();      }    }

来自: http://blog.csdn.net//kingzone_2008/article/details/44571181