美文网首页
JAVA-多线程(二 )两种实现方案

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

作者: lconcise | 来源:发表于2018-10-16 22:45 被阅读9次

方式一 继承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. 适合多个相同程序的代码去处理同一个资源的情况,把线程程序的代码、数据代码有效的分离,较好体现了面向对象的设计思想。

相关文章

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

    方式一 继承Thread类 自定义类MyThread继承Thread 在MyThread 中重写run() 创建M...

  • iOS中GCD学习笔记

    1. iOS中多线程的四种方案 iOS中实现多线程目前有4种方案,最常用的是GCD和NSOperation两种,而...

  • 【iOS开发】--多线程(持续更新)

    文章目录: 一: iOS中多线程的实现方案phreadNSThreadGCDNSOpration 二:多线程的安全...

  • 多线程

    多线程的实现四种基本实现方案 多线程的实现方案.png pthread import

  • IOS---多线程实现方案二 (GCD)

    IOS---多线程实现方案二 (GCD) 上篇文章讨论了使用PTHread和NSThread的多线程实现。这篇文章...

  • IOS2

    一、进程和线程:什么是进程? 什么是线程? 多线程原理? 二、多线程 iOS中多线程实现方案: 1.pthread...

  • iOS开发之多线程基础

    iOS中多线程的实现方案(共四种) pthread、NSThread、GCD、NSOperation 后两种可以说...

  • OC语法_多线程

    1. 多线程实现原理; 2. 多线程实现的方案; 3. 线程同步技术; 1. 多线程实现原理; - 进程:...

  • 多线程(二):实现多线程的两种方式

    一,多线程的实现方式 方式一: 继承Thread类 方式二: 实现Runable接口(推荐) 二,两种方式的区别 ...

  • Java多线程基础知识(上)

    Java多线程实现多线程的实现有两种方式,第一种是继承Thread类,第二种是实现Runnable类.继承Thre...

网友评论

      本文标题:JAVA-多线程(二 )两种实现方案

      本文链接:https://www.haomeiwen.com/subject/gvryoftx.html