Java基础学习----不同种创建线程的区别

今天看了基础视频的线程,发现以前看书学到的东西好少,下面跟大家分享一下,说得多多指教,开始吧!
两种创建线程的方法及区别
两种创建线程的方法:
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. }
  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. }
复制代码
测试结果:

观察结果发现,每个线程对象都有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接口来创建线程类的方法!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值