java实现多线程两种基本方式

    咱们在开发当中常常会使用到多线程,这里咱们来写两个小案例经过最基本的两种方式继承Thread类或实现Runnable接口来实现一个多线程。java

继承Thread类

    咱们能够经过继承Thread类,并重写run()方法的方式来建立一个线程,把线程中须要执行的内容放在run方法当中。多线程

public class ThreadOne extends Thread{
    @Override
    public void run() {
        System.out.println("这是一个继承Thread的多线程");
    }
}

实现Runnable接口

    或者咱们能够经过继承Runnable接口并实现接口中的run()方法的方式来实现一个线程,一样线程中须要执行的内容放在run方法当中。ide

public class ThreadTwo  implements Runnable{
    public void run() {
        System.out.println("这是一个实现Runnable的多线程");
    }
}

    上面仅仅是建立两个线程,咱们还要使用线程,因此咱们要去调用这两个线程,由于实现多线程的方式不一样,因此这两个线程的调用方式也有一些区别。this

    继承Thread的多线程调用方式很简单,只用最普通的方式获取实例便可调用,spa

    下面有两种方式获取实现Runnable接口实例,不过两种方式的实现原理基本相同。被注释的方式为分开写的,即经过两步获取实例,第一步先经过Runnable接口获取对应多线程类的实例,而后第二部将对应多线程实例放入到Thread类中。最后经过获取的实例来调用start()方法启动线程,这里记住线程建立完毕后是不会启动的,只有在调用完start()方法后才会启动。前先后后都绕不开Thread这个类,下面咱们就看看这个类的实现方式。线程

public class MyThread {
    public static void main(String[] args) {
        //继承Thread类
        ThreadOne threadOne = new ThreadOne();
        //实现Runnable接口
        Thread threadTwo = new Thread(new ThreadTwo());
        //另外一种获取实现Runnable接口类的多线程实例的方式
//        Runnable runnable = new ThreadTwo();
//        Thread threadTwo = new Thread(runnable);
        threadOne.start();
        threadTwo.start();
    }
}

    

    首先咱们打开Thread类会发现Thread类也实现了Runnable接口。code

public class Thread implements Runnable

    根据上面两种不一样的方式调用启动线程的方法咱们会发现,这两个方法都是在调用Thread中的start()方法。具体的实现过程能够看java源码。继承

public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();

        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    

    因此java多线程归根结底仍是根据Thread类和Runnable接口来实现的,Thread类也实现了Runnable接口并实现了接口中惟一的run方法。而且Thread把启动线程的start方法定义在本身的类中,因此不管经过哪一种方式实现多线程最后都要调用Thread的start方法来启动线程。这两种方式建立多线程是为了解决java不能多继承的问题,若是某个想使用多线程的类已经拥有父类那么能够经过实现Runnable接口来实现多线程。接口

相关文章
相关标签/搜索