我们在开发当中经常会使用到多线程,这里我们来写两个小案例通过最基本的两种方式继承Thread类或实现Runnable接口来实现一个多线程。
继承Thread类
我们可以通过继承Thread类,并重写run()方法的方式来创建一个线程,把线程中需要执行的内容放在run方法当中。
public class ThreadOne extends Thread{
@Override
public void run() {
System.out.println("这是一个继承Thread的多线程");
}
}
实现Runnable接口
或者我们可以通过继承Runnable接口并实现接口中的run()方法的方式来实现一个线程,同样线程中需要执行的内容放在run方法当中。
public class ThreadTwo implements Runnable{
public void run() {
System.out.println("这是一个实现Runnable的多线程");
}
}
上面仅仅是创建两个线程,我们还要使用线程,所以我们要去调用这两个线程,因为实现多线程的方式不同,所以这两个线程的调用方式也有一些区别。
继承Thread的多线程调用方式很简单,只用最普通的方式获取实例即可调用,
下面有两种方式获取实现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接口。
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接口来实现多线程。