美文网首页
(1)如何开启多线程

(1)如何开启多线程

作者: 一个菜鸟JAVA | 来源:发表于2020-06-30 20:54 被阅读0次

    前言

    学习java多线程首先就是要知道如何开启多线程.在java中开启多线程主要有两种方式:

    • 继承Thread类,然后重写run方法
    • 实现Runnable接口,实现run方法

    示例代码

    public class App1 {
        public static void main(String[] args) {
            create1();
            create2();
        }
    
        /**
         * 继承Thread类,重写run方法
         */
        public static void create1(){
            MyThread thread = new MyThread();
            thread.start();
        }
    
        static class MyThread extends Thread{
            @Override
            public void run() {
                System.out.println("继承Thread类重写run方法创建线程");
            }
        }
    
        /**
         * 实现Runnable接口,实现run方法
         */
        public static void create2(){
            Runnable runnable = new MyRunnable();
            new Thread(runnable).start();
        }
    
        static class MyRunnable implements Runnable{
    
            @Override
            public void run() {
                System.out.println("线程Runnable接口创建线程");
            }
        }
    }
    

    需要注意的是,启动线程是调用start()方法,而不是run方法.run方法只是一个普通的实例方法.

    区别

    一个是通过继承Thread来创建,另一个是通过实现Runnable接口来创建.实际项目开发中,使用Runnable这种方式比较多.而且使用这种方式我们可以通过线程池来执行我们的任务,同时java中只允许单继承.所以比较推荐实现Runnable接口这种方式.当然具体使用哪种方式,只要能完成任务都行.

    相关文章

      网友评论

          本文标题:(1)如何开启多线程

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