JAVA-多线程(二 )两种实现方案

2018-10-16  本文已影响9人  lconcise

方式一 继承Thread类

  1. 自定义类MyThread继承Thread
  2. 在MyThread 中重写run()
  3. 创建MyThread类的对象
  4. 启动线程对象
/**
 * 步骤1,2.
 */
public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("线程一:hello");
    }
}
/**
 * 步骤3,4
 */
public class ThreadDemo {

    public static void main(String args[]) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

方式二 实现runable()接口

  1. 自定义MyRunable()类实现Runable()接口。
  2. 重写run() 。
  3. 创建MyRunable()对象。
  4. 创建Thread 类对象,并把c步骤的对象作为参数传递。
/**
 * 步骤1,2.
 */
public class MyRunable implements Runnable {
    @Override
    public void run() {
        System.out.println("线程二:hello");
    }
}
/**
 * 步骤3.4.
 */
public class ThreadDemo {

    public static void main(String args[]) {
        MyRunable myRunable = new MyRunable();
        Thread myTread = new Thread(myRunable);
        myTread.start();
    }
}

问题

1. 为什么要重写run()方法?

run()方法里封装的是被线程执行的代码

2.启动线程对象是哪个方法?

start()

3. run()和start()区别

run() 直接调用的话 仅仅是普通方法
start() 调用 先启动线程,再由jvm调用run()方法

4. 为什么有了方法一还要有方法二(runable 实现方法)

  1. 可以避免java 单继承带来的局限性
  2. 适合多个相同程序的代码去处理同一个资源的情况,把线程程序的代码、数据代码有效的分离,较好体现了面向对象的设计思想。
上一篇下一篇

猜你喜欢

热点阅读