java--(多线程创建的两种方式Thread类和Runnable接口)

(一)继承Thread类创建多线程----单线程

下面的代码是一个死循环,但是不会执行main里面的循环语句,而是run()里面的语句,这是因为该程序是一个单线程程序,当调用MyThread类的run()方法时,遇到死循环,循环一直进行。因此,MyThread类的打印语句将永远执行,而main()方法中的打印语句无法得到执行。

[html]  view plain  copy
  1. package test;  
  2.   
  3. public class example {  
  4.       public static void main(String[] args){  
  5.           MyThread myThread=new MyThread();  
  6.           myThread.run();  
  7.           while(true)  
  8.           {  
  9.               System.out.println("Main方法在运行");  
  10.           }  
  11.       }  
  12. }  
  13.   
  14. class MyThread{  
  15.     public void run(){  
  16.         while(true){  
  17.             System.out.println("MyThread类的run()方法在运行");  
  18.         }  
  19.     }  
  20. }  

(二)通过继承Thread类实现多线程:
如果希望(一)中的两个循环打印语句都能够执行的话,那么就需要实现多线程。为此jdk提供了一个多线程类Thread,通过继承Thread类,并重写Thread类中的run()方法便可以实现多线程。在Thread类中,提供了一个start()方法用于启动新线程,线程启动后,系统就会自动调用run()方法。

[html]  view plain  copy
  1. package test;  
  2.   
  3. public class example {  
  4.       public static void main(String[] args){  
  5.           MyThread myThread=new MyThread();  
  6.           myThread.start();  
  7.           while(true)  
  8.           {  
  9.               System.out.println("Main方法在运行");  
  10.           }  
  11.       }  
  12. }  
  13.   
  14. class MyThread extends Thread{  
  15.     public void run(){  
  16.         while(true){  
  17.             System.out.println("MyThread类的run()方法在运行");  
  18.         }  
  19.     }  
  20. }  

(三)实现Runnable接口创建多线程
在(二)中通过继承Thread类实现多线程,但是这种方式有一定的局限性。因为在java中只支持单继承,一个类一旦继承了某个父类就无法再继承Thread类,比如学生类Student继承了person类,就无法再继承Thread类创建的线程。为了克服这种弊端,Thread类提供了另外一种构造方法Thread(Runnable target),其中Runnable是一个接口,它只有一个run()方法。当通过Thread(Runnable target)构造方法创建一个线程对象时,只需该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了Runnable接口中的run()方法作为运行代码,二不需要调用Thread类中的run()方法。

[html]  view plain  copy
  1. package test;  
  2.   
  3. public class example {  
  4.       public static void main(String[] args){  
  5.           MyThread myThread=new MyThread();  
  6.           Thread thread=new Thread(myThread);  
  7.           thread.start();  
  8.           while(true)  
  9.           {  
  10.               System.out.println("Main方法在运行");  
  11.           }  
  12.       }  
  13. }  
  14.   
  15. class MyThread implements Runnable{  
  16.     public void run(){  
  17.         while(true){  
  18.             System.out.println("MyThread类的run()方法在运行");  
  19.         }  
  20.     }  
  21. }  


转载自:https://blog.csdn.net/qq_32823673/article/details/78657281


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值