Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2222871
  • 博文数量: 556
  • 博客积分: 11457
  • 博客等级: 上将
  • 技术积分: 5973
  • 用 户 组: 普通用户
  • 注册时间: 2011-02-24 22:33
文章分类

全部博文(556)

文章存档

2013年(22)

2012年(74)

2011年(460)

分类: Java

2011-09-24 13:55:19

  1. package cn.itcast.heima;

  2. public class TraditionalThread {

  3.     /**
  4.      * @param args
  5.      */
  6.     public static void main(String[] args) {
  7.         Thread thread = new Thread() {
  8.             @Override
  9.             public void run() {

  10.                 while (true) {
  11.                     try {
  12.                         Thread.sleep(500);
  13.                     } catch (InterruptedException e) {

  14.                         e.printStackTrace();
  15.                     }
  16.                     System.out.println(Thread.currentThread().getName());
  17.                 }
  18.             }

  19.         };
  20.         thread.start();

  21.         Thread thread2=new Thread(new Runnable(){
  22.             @Override
  23.             public void run() {
  24.                 while (true) {
  25.                     try {
  26.                         Thread.sleep(500);
  27.                     } catch (InterruptedException e) {

  28.                         e.printStackTrace();
  29.                     }
  30.                     System.out.println(Thread.currentThread().getName());

  31.                 }

  32.             }

  33.         });
  34.         thread2.start(); //让第二个线程也运行,则他就执行Thread()内部的run()方法。

  35.         new Thread( new Runnable(){
  36.             public void run() {
  37.                 while (true) {
  38.                     try {
  39.                         Thread.sleep(500);
  40.                     } catch (InterruptedException e) {

  41.                         e.printStackTrace();
  42.                     }
  43.                     System.out.println("runnable:" Thread.currentThread().getName());

  44.                 }
  45.             };
  46.         }
  47.         ){
  48.             public void run() {

  49.                 while (true) {
  50.                     try {
  51.                         Thread.sleep(500);
  52.                     } catch (InterruptedException e) {

  53.                         e.printStackTrace();
  54.                     }
  55.                     System.out.println("Thread:" Thread.currentThread().getName());

  56.                 }

  57.             };

  58.         }.start();

  59.     }
  60. }

创建线程的两种方式:

1.在Thread子类覆盖的run方法中编写运行代码

2.在传递给Thread对象的Runnable对象的run方法中编写代码

总结

查看Thread类的run()方法的源码,可以看到其实这两种方式都是在调用Thread对象的run()方法,如果Thread类的run()方法没有被覆盖,并且为该Thread对象设置了一个Runnable对象,该run方法会调用Runnable对象的run()方法。

阅读(997) | 评论(0) | 转发(0) |
0

上一篇:CMM的体系结构

下一篇:树形组织结构

给主人留下些什么吧!~~