zoukankan      html  css  js  c++  java
  • 创建新线程的两种方法比较

    //方法一:从Thread派生一个自定义类,然后覆写run()方法:
    public class Main {
        public static void main(String[] args) {
            Thread t = new MyThread();
            t.start(); // 启动新线程
        }
    }
    
    class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("start new thread!");
        }
    }
    //方法二:创建Thread实例时,传入一个Runnable实例:
    public class Main {
        public static void main(String[] args) {
            Thread t = new Thread(new MyRunnable());
            t.start(); // 启动新线程
        }
    }
    
    class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println("start new thread!");
        }
    }

    实现Runnable接口创建多线程程序的好处:

    1.避免了单继承的局限性

     一个类只能继承一个类,类继承了Thread类就不能进继承其他类,实现了Runnable接口,还可以继承其他类,实现其他接口。

    2.增强了程序的扩展性,降低了程序的耦合性

    把设置线程任务和开启新线程进行了分离,可以通过传入不同的Runnable接口实现类,实现不同的功能。

  • 相关阅读:
    python注释中文
    python学习好文
    浅析python 的import 模块(转)
    Python解释器镜像源修改
    Python解释器安装
    Python和Python解释器
    计算机基础小结
    网络瓶颈效应
    编程语言分类
    子查询|视图事务
  • 原文地址:https://www.cnblogs.com/try4396/p/12146504.html
Copyright © 2011-2022 走看看