Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2553290
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2011-12-05 16:59:22

在jdk中有一个Thread(Runnable target)构造方法。Runnable接口只有一个run方法。

当使用Thread(Runnable target)方法创建线程对象时,需为该方法传递一个Runnable接口的类对象。这样创建的线程将调用那个实现了Runnable接口的类对象中的run方法作为其运行代码,而不再调用Thread类中的run方法。


  1. public class ThreadDemo3 {

  2.     public static void main(String[] args) {
  3.         
  4.         TestThread3 tt = new TestThread3();
  5.         Thread t = new Thread(tt);
  6.         t.start();
  7.         while(true){
  8.             System.out.println("main thread is runing...");
  9.             try {
  10.                 Thread.currentThread().sleep(1000);
  11.             } catch (InterruptedException e) {
  12.                 e.printStackTrace();
  13.             }
  14.         }
  15.     }
  16. }

  17. class TestThread3 implements Runnable{

  18.     @Override
  19.     public void run() {
  20.         while(true){
  21.             System.out.println(Thread.currentThread().getName() + " is runing***");
  22.             try {
  23.                 Thread.sleep(1000);
  24.             } catch (InterruptedException e) {
  25.                 e.printStackTrace();
  26.             }
  27.         }
  28.         
  29.     }
  30.     
  31. }
测试运行结果:
main thread is runing...
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
main thread is runing...
Thread-0 is runing***
Thread-0 is runing***

实现runnable接口相对于继承Thread类来说,有如下好处:
适合多个相同程序代码的线程去处理同一资源的情况。
可以避免由于java的单继承带来的局限。
代码能被多个线程共享,代码与数据是独立的。

事实上,几乎所有的多线程应用都可通过实现Runnable接口来实现。
阅读(800) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~