你们都知道多线程能够经过两种方式来建立。 java
1、经过继承Thread类 编程
2、经过实现Runnable接口 多线程
那么中两种方式到底有什么区别呢?那种方式更好些呢? spa
咱们使用多线程,无非就是想利用多线程的优势,来更好的实现咱们的想法。 线程
多线程有哪些优势呢? 对象
1、多线程共享同一块内存空间和一组系统资源 blog
2、线程自己的数据一般都是只有微处理器的寄存器数据,以及供程序执行的堆栈。因此系统在产生一个线程或者线程的切换要比进程系统的负担小不少。 继承
如今咱们来了解一些Thread类。 接口
-
public class ThreadDemo 进程
- {
- public static void main(String []args)
- {
- ThreadTest t=new ThreadTest();
- t.start();
- t.start();
- t.start();
- t.start();
- }
- }
- class ThreadTest extends Thread
- {
- private int count=10;
- public void run()
- {
- while(count>0)
- {
- System.out.println(Thread.currentThread().getName()+" "+count--);
- }
- }
- }
运行后,咱们发现其实只启动了一个线程。
是否是程序有问题呢?咱们修改一下程序。
- public class ThreadDemo
- {
- public static void main(String []args)
- {
- new ThreadTest().start();
- new ThreadTest().start();
- new ThreadTest().start();
- new ThreadTest().start();
- }
- }
- class ThreadTest extends Thread
- {
- private int count=10;
- public void run()
- {
- while(count>0)
- {
- System.out.println(Thread.currentThread().getName()+" "+count--);
- }
- }
- }
再次运行,发现这四个线程对象各自占有各自的资源,并非同时完成统一任务。
咱们能够得出结论:Thread类实际上没法达到资源共享的目的。
那么,Runnable接口能不能达到这一目的呢?
咱们大可试一下。
- public class ThreadDemo
- {
- public static void main(String []args)
- {
- ThreadTest test=new ThreadTest();
- new Thread(test).start();
- new Thread(test).start();
- new Thread(test).start();
- new Thread(test).start();
- }
- }
- class ThreadTest implements Runnable
- {
- private int count=10;
- public void run()
- {
- while(count>0)
- {
- System.out.println(Thread.currentThread().getName()+" "+count--);
- }
- }
- }
运行以后咱们发现,这四个线程同时完成了咱们须要完成的任务。
经过以上比较咱们便可得出Thread与Runnable的区别:
一、Runnable适合于多个相同程序代码线程去处理统一资源的状况,把虚拟的cpu(线程)同程序的代码,数据有效分离,较好体现面向对象的编程的思想
二、Runnable能够避免因为java的单继承机制带来的局限。能够再继承其余类的同时,还能实现多线程的功能。
三、Runnable能增长程序的健壮性。代码可以被多个线程共享。