初识 Java 多线程

前言

不论是在技术学习的路线上,还是在面试中,多线程与并发出现的频率越来越高。所以不难看出这也是我们需要重点学习的一部分内容,今天的主要内容就是初识Java多线程,掌握线程的几种创建方式,以及多线程中的静态代理。

正文

首先,先理清楚三个概念:程序、进程、线程。
我们平时写的代码叫做程序,当程序运行起来的时候就成为一个进程,进程中又有许多线程在执行。

什么是多线程呢?请看下图
在这里插入图片描述
上图左边的部分就是我们平常写代码的流程,在主线程(main)中调用run方法,主线程切换出去去执行run()方法,执行完毕后返回,继续执行main函数中后续的代码。

右图则是在主线程中调用了Thread.start()方法,这时候会启动一个子线程,由它去执行run()方法,此时有两条线程(主线程和子线程)路径,交替轮流执行。

可以看出多线程是同时执行的,也就是说可以支持同时执行不同的操作。比如我们平时看电影的时候,既能够看到画面,同时也能够听到声音,这就是利用了多线程。

创建线程的几种方式

线程的创建方式有三种

  • 继承Thread
  • 实现Runnable接口
  • 实现Callable接口

下面我们就利用这三种方式分别创建线程,并分析其各自的特点。

继承Thread类

采用继承Thread类的方式实现多线程,可以分为以下几个步骤:

  1. 重写run()方法
  2. 实例化线程类,调用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接口创建多线程需要借助两个类:ExecutorServiceExecutors。创建步骤如下:

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()方法时,想必你的答案一定能够惊艳到他!

总结

今天我们了解了如何创建多线程,不同创建方式之间的区别,以及多线程中的静态代理。多线程的世界纷乱复杂,资源争夺、变量值不唯一…下次我们再看一看锁是如何将线程的世界一一理顺的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

steven_moyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值