Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2339777
  • 博文数量: 2110
  • 博客积分: 18861
  • 博客等级: 上将
  • 技术积分: 24420
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-05 18:23
文章分类

全部博文(2110)

文章存档

2011年(139)

2010年(1971)

我的朋友

分类: Java

2010-08-23 13:15:47

 

  但是在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。此时观察Thread类,有一个构造方法:public Thread(Runnable targer)

  此构造方法接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现的多

  线程。(start()可以协调系统的资源):

  package org.runnable.demo;

  import org.runnable.demo.MyThread;

  public class ThreadDemo01 {

  public static void main(String[] args) {

  MyThread mt1=new MyThread("线程a");

  MyThread mt2=new MyThread("线程b");

  new Thread(mt1).start();

  new Thread(mt2).start();

  }

  }

  · 两种实现方式的区别和联系:

  在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比

  继承Thread类有如下好处:

  ->避免点继承的局限,一个类可以继承多个接口。

  ->适合于资源的共享

  以卖票程序为例,通过Thread类完成:

  package org.demo.dff;

  class MyThread extends Thread{

  private int ticket=10;

  public void run(){

  for(int i=0;i<20;i++){

  if(this.ticket>0){

  System.out.println("卖票:ticket"+this.ticket--);

  }

  }

  }

  };

  下面通过三个线程对象,同时卖票:

  package org.demo.dff;

  public class ThreadTicket {

  public static void main(String[] args) {

  MyThread mt1=new MyThread();

  MyThread mt2=new MyThread();

  MyThread mt3=new MyThread();

  mt1.start();//每个线程都各卖了10张,共卖了30张票

  mt2.start();//但实际只有10张票,每个线程都卖自己的票

  mt3.start();//没有达到资源共享

  }

  }

  如果用Runnable就可以实现资源共享,下面看例子:

  package org.demo.runnable;

  class MyThread implements Runnable{

  private int ticket=10;

  public void run(){

  for(int i=0;i<20;i++){

  if(this.ticket>0){

  System.out.println("卖票:ticket"+this.ticket--);

  }

  }

  }

  }

  package org.demo.runnable;

  public class RunnableTicket {

  public static void main(String[] args) {

  MyThread mt=new MyThread();

  new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一

  new Thread(mt).start();//个实例化对象mt,就会出现异常

  new Thread(mt).start();

  }

  };

  虽然现在程序中有三个线程,但是一共卖了10张票,也就是说使用Runnable实现多线程可以达到资源共享目的。

  Runnable接口和Thread之间的联系:

  public class Thread extends Object implements Runnable

  发现Thread类也是Runnable接口的子类。

阅读(241) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~