A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 孙小亚 中级黑马   /  2014-8-16 18:47  /  1398 人查看  /  4 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

今天看了基础视频的线程,发现以前看书学到的东西好少,下面跟大家分享一下,说得多多指教,开始吧!
两种创建线程的方法及区别
两种创建线程的方法:
1.继承Thread类,格式:class  线程名 extends Thread
  1. class myThread extends Thread{}
复制代码

2.实现Runnable接口,格式:class 线程名 implements Runnable
  1. class myThread implements Runnable{}
复制代码
区别:目的:创建三个线程一起卖票,用两种方法做,看实际效果
方法1(继承Thread类):

  1. public class ThreadDemo1 {

  2.         public static void main(String[] args) {
  3.                 new Thread1().start();
  4.                 new Thread1().start();
  5.                 new Thread1().start();
  6.         }
  7. }
复制代码
测试结果:

观察结果发现,每个线程对象都有5张票,每个线程卖自己的5张票,没有共享这5张票。

方法2(实现Runnable接口):
  1. public class ThreadDemo1 {

  2.         public static void main(String[] args) {
  3.                 Thread1 t1 = new Thread1();
  4.                 new Thread(t1).start();
  5.                 new Thread(t1).start();
  6.                 new Thread(t1).start();
  7.         }
  8. }
  9.         class Thread1 implements Runnable{
  10.         int tickets =20;  //为了测试出效果,可以多增加票数
  11.         public  void run(){
  12.                 while(true){
  13.                         if(tickets > 0)
  14.                         System.out.println("run() at "+Thread.currentThread().getName()+" is saling "+tickets--);
  15.                 }
  16.         }
  17. }
复制代码
测试结果:

观察发现,达到了目的,三个线程在一起共享这20张票。
总结:
1.继承Thread来创建线程类的方法,在继承了Thread后,不能再继承其他类,这样灵活性就不如实现Runnable接口来创建线程类的方法了;
2.正如上面所说的使用实现Runnable接口来创建线程类的方法可以达到资源共享。

在这里说明一下:继承Thread类来创建线程类的方法也可以实现资源共享,只不过比较麻烦!!!因此,在创建线程类的时候,应优先选择实现Runnable接口来创建线程类的方法!!!





4 个回复

倒序浏览
sorry,帖子出了点小问题。修复。。。
方法1(继承Thread类):
  1. public class ThreadDemo1 {

  2.         public static void main(String[] args) {
  3.                 new Thread1().start();
  4.                 new Thread1().start();
  5.                 new Thread1().start();
  6.         }
  7. }
  8.         class Thread1 extends Thread{
  9.         int tickets =5;  //5张票
  10.         public  void run(){
  11.                 while(true){
  12.                         if(tickets > 0)
  13.                         System.out.println("run() at "+Thread.currentThread().getName()+" is saling "+tickets--);
  14.                 }
  15.         }
  16. }
复制代码
回复 使用道具 举报
方法1的测试结果:
回复 使用道具 举报
孙小亚 发表于 2014-8-16 18:54
方法1的测试结果:

继承thread类会出现两个窗口买一张票的情况吗?
回复 使用道具 举报
贾浩田 发表于 2014-8-17 11:58
继承thread类会出现两个窗口买一张票的情况吗?

每个线程对象都有自己的tickets,不是所有的线程类都共享一个tickets
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马