前言
不论是在技术学习的路线上,还是在面试中,多线程与并发出现的频率越来越高。所以不难看出这也是我们需要重点学习的一部分内容,今天的主要内容就是初识Java多线程,掌握线程的几种创建方式,以及多线程中的静态代理。
正文
首先,先理清楚三个概念:程序、进程、线程。
我们平时写的代码叫做程序,当程序运行起来的时候就成为一个进程,进程中又有许多线程在执行。
什么是多线程呢?请看下图
上图左边的部分就是我们平常写代码的流程,在主线程(main)中调用run
方法,主线程切换出去去执行run()
方法,执行完毕后返回,继续执行main函数中后续的代码。
右图则是在主线程中调用了Thread.start()
方法,这时候会启动一个子线程,由它去执行run()
方法,此时有两条线程(主线程和子线程)路径,交替轮流执行。
可以看出多线程是同时执行的,也就是说可以支持同时执行不同的操作。比如我们平时看电影的时候,既能够看到画面,同时也能够听到声音,这就是利用了多线程。
创建线程的几种方式
线程的创建方式有三种
- 继承
Thread
类 - 实现
Runnable
接口 - 实现
Callable
接口
下面我们就利用这三种方式分别创建线程,并分析其各自的特点。
继承Thread类
采用继承Thread
类的方式实现多线程,可以分为以下几个步骤:
- 重写
run()
方法 - 实例化线程类,调用
start()
方法
public class Thread_01 extends Thread{
// 重写run()方法
public void run() {
for(int i=0; i<100; i++) {
System.out.println("Thread_01线程值为---->" + i);
}
}
public static void main(String[] args) {
// 实例化线程类对象
Thread_01 thread_01 = new Thread_01();
// 调用start()方法
thread_01.start();
for(int i=0; i<100; i++) {
System.out.println("main线程的值为--->" + i);
}
}
}
上面的代码中有两个线程,一个是main
线程,另一个是我们通过new操作符创建的thread_01
线程。运行之后可以发现main
线程和子线程交替输出,说明两个线程是交替执行的。
实现Runnable接口
通过实现Runnable
接口来创建线程同样需要重写run()
方法,所不同的是在创建的时候,需要new
一个Thread
对象,然后将Runnable实现类的对象当做参数传进去。形式如:new Thread(Runnable实现类的对象)
。
public class Thread_03 implements Runnable{
// 重写run()方法
@Override
public void run() {
for(int i=0; i<100; i++) {
System.out.println(Thread.currentThread().getName() + "在学习多线程");
}
}
public static void main(String[] args) {
// 创建Runnable接口的实现类
Thread_03 thread03 = new Thread_03();
// new Thread(),并将Runnable接口实现类传入,调用start()方法
new Thread(thread03).start();
for(int i=0; i<100; i++) {
System.out.println(Thread.currentThread().getName() + "在学习敲代码");
}
}
}
实现Runnable
接口来创建线程是比较推荐的一种方式,相比于直接继承Thread
类,实现Runnable
接口更具有灵活性,它可以实现多个线程对同一对象的操作,在上面的例子中我们可以再创建一个线程,该线程也对thread03
进行操作,new Thread(thread03).start();
。
下面举一个更直观的例子来说明这一点,采用多线程来模拟龟兔赛跑,有兔子和乌龟两个线程,共用同一条跑道,若有一方到达终点,比赛即为结束。
public class Thread_04_Race implements Runnable{
private static String winner;
@Override
public void run() {
for(int i=0; i<=100; i++) {
if(Thread.currentThread().getName().equals("兔子")) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i);
if (flag) {
break;
}
System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
}
}
public boolean gameOver(int steps) {
if(winner != null) {
return true;
}
if(steps >= 100) {
winner = Thread.currentThread().getName();
System.out.println("winner is " + winner);
return true;
}
return false;
}
public static void main(String[] args) {
Thread_04_Race race = new Thread_04_Race();
new Thread(race, "兔子").start();
new Thread(race, "乌龟").start();
}
}
在这个例子中,兔子和乌龟两个线程操作同一个对象race
,对race
对象中的winner
变量进行赋值。采用继承Thread类的方式则无法使得多个线程操作同一个对象,该方式无疑增加了多线程的灵活性。
实现Callable接口
相比于前两种方式,实现Callable接口来创建多线程不是很常用,也相对来说有点复杂。但是通过该方式创建多线程可以具有返回值,回顾前两种方式,我们都需要重写一个 void run()
方法,该方法是没有返回值的。实现Callable接口时,需要重写一个T call()
方法,该方法返回一个类型为T
的值。
通过实现Callable接口创建多线程需要借助两个类:ExecutorService
和Executors
。创建步骤如下:
1、重写call()方法
public class ThreadCall() {
@Override
public Boolean call() {
System.out.println("我是子线程,call()方法已被重写!");
return true;
}
}
2、创建线程
创建线程的整个过程可以分为4步:创建执行服务、提交执行服务、获取执行结果、关闭服务。
ThreadCall t1 = new ThreadCall();
// 1. 创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(1); //1-->表示线程池中有一个线程
// 2. 提交执行服务
Future<Boolean> r1 = executorService.submit(t1);
// 3. 获取执行结果
boolean rs1 = r1.get();
// 4. 关闭服务
executorService.shutdownNow();
静态代理
代理:简单来说,代理就是让别人来代替你完成你想要做的事情。比如租房子时的中介、点外卖时的美团、饿了么配送员,他们充当的就是一个代理的角色。具体到代码中,委托类(你)和代理类(中介)要实现同一个接口,代理类负责一些消息的处理,并不实现真正的服务,真正的服务需要调用委托类的对象来实现。这就好比你要租房子,中介(代理类)只会帮你联系房东、挑选合适的房子,但租房的费用(真正的服务)还是需要你(委托类的对象)来支付的,中介并不会帮你支付这笔费用。
既然说到了静态代理,那么一定还有一个叫做动态代理的东西,下面简单列出二者的区别,本文不再过多阐述。
回顾我们实现多线程的方法,首先实现了Runnable
接口,接着创建了Runnable
接口实现类的对象target
,然后通过new Thread(target)
创建多线程,最后调用Thread.start()
方法启动线程。下面来看一看这一过程在究竟是如何执行的:
Thread 源码分析
/* What will be run. */
private Runnable target;
这里的target
就是我们new Thread(target)
时传入的Runnable
实现类的对象,也是委托类。Thread
则是代理类。
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 */
}
}
}
private native void start0();
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
我们在启动线程时调用start()
方法,在start()
方法内部调用了start0()
方法,start0()
是一个本地方法,在线程执行时,它又会调用run()
方法。注意调用run()
方法时,实际上执行的是target.run()
,也就是我们覆写的那个run()
方法,即委托类的run()
方法。
这样分析下来,不难发现多线程的实现其实是一种静态代理的模式,Thread
充当代理类,Runnable
的实现类充当委托类,既然代理类是通过调用委托类对象的方法来实现真正的服务的,那么自然需要委托类实现相应的方法,这也就是为什么一定需要重写run()
方法的原因了。下次面试官再问到为什么要重写run()方法时,想必你的答案一定能够惊艳到他!
总结
今天我们了解了如何创建多线程,不同创建方式之间的区别,以及多线程中的静态代理。多线程的世界纷乱复杂,资源争夺、变量值不唯一…下次我们再看一看锁是如何将线程的世界一一理顺的。