黑马程序员技术交流社区

标题: 多线程的学习心得体会 [打印本页]

作者: qinpeiwei881211    时间: 2015-5-21 11:50
标题: 多线程的学习心得体会
     Java提供了两种多线程的实现方式:一种是继承Java.lang包中的Thread类,覆写了Thread类中的run()方法,在run()方法中实现运行在线程上的代码,一种是实现java.lang中的Runnable接口,同样在run()方法中实现运行在线程上的代码。
  1. public class Example
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 MyThread  mt = new MyThread();//创建一个Thread的线程对象。
  6.                 mt.start();//开启线程。
  7.                 while(ture)//通过循环语句打印输出
  8.                 {
  9.                         System.out.println("main()方法运行了");
  10.                 }
  11.         }
  12. }
  13. class MyThread extends Thread
  14. {
  15.         public void run()
  16.         {
  17.                 while(ture)
  18.                 {
  19.                         System.out.println("run方法运行了");
  20.                 }
  21.         }
  22. }
复制代码
以上代码继承了Thread类实现了多线程,但是这种方法有一定的局限性,因为在Java中只支持单继承,一个类继承了父类就无法在继承其他的类,为了克服这种弊端,Thread类提供了另外一个构造方法Thread(Runnable target),其中Runnable是一个接口,他就只有一个run()方法,当通过这个构造方法创建线程对象时,只需要该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了接口中的run()方法作为运行的代码,而不需要调用Therad类中的run()方法。所以以上代码是有局限性的。
  1. public class Example
  2. {
  3.         public static void main(String[] args)
  4.         {
  5.                 MyThread  mt = new MyThread();//创建一个Thread的线程对象。
  6.                 Thread t = new Thread(MyThread);//创建线程对象。
  7.                 t.start();//开启线程。
  8.                 while(ture)//通过循环语句打印输出
  9.                 {
  10.                         System.out.println("main()方法运行了");
  11.                 }
  12.         }
  13. }
  14. class MyThread implements Runnable
  15. {
  16.         public void run()
  17.         {
  18.                 while(ture)
  19.                 {
  20.                         System.out.println("run方法运行了");
  21.                 }
  22.         }
  23. }
复制代码
以上代码实现了Runnable接口,并重写了Runnable接口中的run()方法,通过Thread类的构造函数将MyThread类的实例化对象作为参数传入,main()方法和run()方法中的打印语句都指向那个了。这样就实现了多线程。






作者: 菜鸟的求学路    时间: 2015-5-21 11:57
好    学习就行啊  我这是挣点就走
作者: qinpeiwei881211    时间: 2015-5-21 12:09
菜鸟的求学路 发表于 2015-5-21 11:57
好    学习就行啊  我这是挣点就走

呵呵,不好挣啊
作者: hkbat    时间: 2015-5-21 12:22
一直搞不懂多线程。
作者: qinpeiwei881211    时间: 2015-5-21 12:24
hkbat 发表于 2015-5-21 12:22
一直搞不懂多线程。

买本书 好好看看:loveliness:
作者: yas丶    时间: 2015-5-21 14:18
学习下,
作者: qinpeiwei881211    时间: 2015-5-21 14:30
yas丶 发表于 2015-5-21 14:18
学习下,

:loveliness:
作者: 你们敬爱的人    时间: 2015-5-21 16:52
- - 6666666666666
作者: qinpeiwei881211    时间: 2015-5-21 16:57
你们敬爱的人 发表于 2015-5-21 16:52
- - 6666666666666

:lol。。。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2