526  
查询码: 00000393
java开启新线程的三种方法
作者: 系统管理员 于 2018年03月09日 发布在分类 / 技术研发 / 开源组件 ,于 2018年03月09日 编辑
线程 thread 方法 启动 方式 实现 继承 执行 创建 一个


方式1:继承 Thread

步骤:

1):定义一个类 A 继承于 Java.lang.Thread .

2): A 类中覆盖 Thread 类中的 run 方法 .

3):我们在 run 方法中编写需要执行的操作: run 方法里的代码 , 线程执行体 .

4): main 方法 ( 线程 ) , 创建线程对象 , 并启动线程 .

(1)创建线程类对象 :

A a  =  new   A ();

(2)调用线程对象的 start 方法 :

a.start();//启动一个线程


注意:千万不要调用 run 方法 , 如果调用 run 方法好比是对象调用方法 , 依然还是只有一个线程 , 并没有开启新的线程 .

线程只能启动一次!

创建启动线程实例:

[java] view plain copy

  1. //1):定义一个类A继承于java.lang.Thread类.
  2. class MusicThread extends Thread{
  3. //2):在A类中覆盖Thread类中的run方法.
  4. public void run() {
  5. //3):在run方法中编写需要执行的操作
  6. for ( int i = 0 ; i < 50 ; i ++){
  7. System.out.println("播放音乐" +i);
  8. }
  9. }
  10. }

  11. public class ExtendsThreadDemo {
  12. public static void main(String[] args) {

  13. for ( int j = 0 ; j < 50 ; j ++){
  14. System.out.println("运行游戏" +j);
  15. if (j == 10 ){
  16. //4):在main方法(线程)中,创建线程对象,并启动线程.
  17. MusicThread music = new MusicThread();
  18. music.start();
  19. }
  20. }
  21. }

  22. }


方式2:实现 Runnable 接口

步骤:

1):定义一个类 A 实现于 java.lang.Runnable 接口 , 注意 A 类不是线程类 .

2): A 类中覆盖 Runnable 接口中的 run 方法 .

3):我们在 run 方法中编写需要执行的操作: run 方法里的 , 线程执行体 .

4): main 方法 ( 线程 ) , 创建线程对象 , 并启动线程 .

     (1)创建线程类对象 :

     Thread  t = new Thread(new  A());

     (2)调用线程对象的 start 方法 :

     t.start();


[java] view plain copy

  1. //1):定义一个类A实现于java.lang.Runnable接口,注意A类不是线程类.
  2. class MusicImplements implements Runnable{
  3. //2):在A类中覆盖Runnable接口中的run方法.
  4. public void run() {
  5. //3):在run方法中编写需要执行的操作
  6. for ( int i = 0 ; i < 50 ; i ++){
  7. System.out.println("播放音乐" +i);
  8. }

  9. }
  10. }

  11. public class ImplementsRunnableDemo {
  12. public static void main(String[] args) {
  13. for ( int j = 0 ; j < 50 ; j ++){
  14. System.out.println("运行游戏" +j);
  15. if (j == 10 ){
  16. //4):在main方法(线程)中,创建线程对象,并启动线程
  17. MusicImplements mi = new MusicImplements();
  18. Thread t = new Thread(mi);
  19. t.start();
  20. }
  21. }
  22. }

  23. }

分析继承方式和实现方式的区别:

继承方式:
1):从设计上分析,Java中类是单继承的,如果继承了Thread了,该类就不能再有其他的直接父类了.
2):从操作上分析,继承方式更简单,获取线程名字也简单.(操作上,更简单)
3):从多线程共享同一个资源上分析,继承方式不能做到.
实现方式:
1):从设计上分析,Java中类可以多实现接口,此时该类还可以继承其他类,并且还可以实现其他接口,设计更为合理.
2):从操作上分析,实现方式稍微复杂点,获取线程名字也比较复杂,得使用Thread.currentThread()来获取当前线程的引用.

               3):从多线程共享同一个资源上分析,实现方式可以做到(是否共享同一个资源).


补充:实现方式获取线程名字:

String name = Thread.currentThread().getName();




方式3:直接在函数体使用(匿名内部类,其实也是属于第二种实现方式的特例。)

[cpp] view plain copy

  1. void java_thread()
  2. {

  3. Thread t = new Thread( new Runnable(){
  4. public void run(){
  5. // run方法具体重写
  6. mSoundPoolMap.put(index, mSoundPool.load(filePath, index));
  7. getThis().LoadMediaComplete();
  8. }});
  9. t.start();
  10. }
0人参与


 历史版本

备注 修改日期 修改人
CREAT 2018-03-09 11:58:13[当前版本] 系统管理员

  目录
    wcp知识库系统-京ICP备15024440号-1 -V 5.1.9 -wcp