一篇简单易懂的Java多线程基础文章

640?wx_fmt=png


今日科技快讯


近日德国媒体WELT发表了一篇以华为消费者业务CEO余承东为采访对象的专访文章。文章中,当被问及华为是否会打造自己到底操作系统以便在智能手机和电脑业务中摆脱对Google或微软的依赖时,余承东表示:我们已经准备了自己的操作系统。一旦发生了我们不能够在使用这些操作系统的情况,我们需要做好准备。这是B计划。然而,我们当然更喜欢与Google和微软这样的生态伙伴来合作。


作者简介


大家周一好,新的一周继续努力加油吧!

本篇文章来自 三刀流剑客 的投稿,和大家分享了Java多线程相关的知识,希望对大家有所帮助!

三刀流剑客 的博客地址

https://www.jianshu.com/u/ea4b5d51b1c4


前言


线程:程序执行流的最小单元【可以理解为:进程中独立运行的子任务】。

多线程优点:最大限度的利用CPU的空闲时间来处理其他任务。


正文


创建线程

  • 线程的创建方式

继承Thread类

public class ThreadCreateDemo1 {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); //该方法调用多次,出现IllegalThreadStateException
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        super.run();
        System.out.println("hellow_world!");
    }
}

实现Runnable接口

public class ThreadCreateDemo2 {
    public static void main(String[] args) {
        Runnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        thread.start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("通过Runnable创建的线程!");
    }
}

上述两种创建方式,工作时性质一样。但是建议使用实现Runable接口方式。解决单继承的局限性。

线程运行结果与执行顺序无关

线程的调度是由CPU决定,CPU执行子任务时间具有不确定性。

public class ThreadRandomDemo1 {
    public static void main(String[] args) {
        Thread[] threads = new Thread[10];
        for (int i = 0; i < 10; i++) {
            threads[i] = new RandomThread("RandomThread:" + i);
        }
        for(Thread thread : threads) {
            thread.start();
        }
    }
}

class RandomThread extends Thread {

    public RandomThread(String name) {
        super(name);
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

以上10个线程,代码按照顺序执行,但是结果可以看出没有按照顺序执行,而且多次执行结果基本不同。

640?wx_fmt=jpeg

图1-1 随机线程被执行

线程实例变量与安全问题

线程之间变量有共享与不共享之分,共享理解为大家都使用同一份,不共享理解为每个单独持有一份。

  • 共享数据情况

public class ThreadShareVariableDemo {
    public static void main(String[] args) {
        Runnable runnable = new ShareVariableRunnable();
        Thread[] threads = new Thread[5];
        for (int i = 0; i < 5; i++) {
            threads[i] = new Thread(runnable, "thread:" + (i+1));
        }
        for (Thread thread : threads) {
            thread.start();
        }
    }
}

class ShareVariableRunnable implements Runnable {
    private int count = 5;

    public void run() {
        System.out.println("" + Thread.currentThread().getName() + ",count:" + count--);
    }
}

640?wx_fmt=jpeg

图1-2 线程共享变量

从上图结果可以看出,count变量是共享的,不然都会打印4。但是也发现了一点thread:1 与 thread:2 打印值一样,该现象就是我们通常称为的脏数据【多线程对同一变量进行读写操作不同步产生】。

解决方案在访问变量方法中增加synchronized关键字:

class ShareVariableRunnable implements Runnable {
    private int count = 5;

    public synchronized void run() {
        System.out.println("" + Thread.currentThread().getName() + ",count:" + count--);
    }
}

640?wx_fmt=jpeg

图1-3 线程共享变量安全

如图每次打印count都是正常递减,这里解释一下synchronized关键字,含有synchronized关键字的这个方法称为“互斥区” 或“临界区”,只有获得这个关键字对应的锁才能执行方法体,方法体执行完自动会释放锁。

停止线程

终止正在运行的线程方法有三种:

  1. 使用退出标志,使线程正常的执行完run方法终止。

  2. 使用interrupt方法,使线程异常,线程进行捕获或抛异常,正常执行完run方法终止。

  3. 使用stop方法强制退出。

这里主要说明前两种方法;

  • 使用退出标志方法

public class ThreadVariableStopDemo {
    public static void main(String[] args) throws InterruptedException {
        VariableStopThread thread = new VariableStopThread("thread_1");
        thread.start();
        Thread.sleep(1);
        thread.Stop();
    }
}

class VariableStopThread extends Thread {
    private boolean interrupt = true;

    public VariableStopThread(String name) {
        super(name);
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + ":线程开始运行!");
        int i = 0;
        while(interrupt) {
            System.out.println("" + (i++));
        }
        System.out.println("我停止了! timer:" + System.currentTimeMillis());
    }

    public void Stop() {
        System.out.println(Thread.currentThread().getName() + ":线程设置了停止! timer:" + System.currentTimeMillis());
        this.interrupt = false;
    }
}

640?wx_fmt=jpeg

图1-4 线程退出

Thread_1中启动了一个while循环,一直打印i的累加值。main线程在sleep 1ms后设置Thread_1停止标志。Thread_1 while循环判断条件不符合正常执行完run方法结束。从【图1-4 线程退出】中可以看出设置完停止标志后13还是正常打印,原因是因为while方法体中是原子操作,不能直接打断。

在使用终止线程方法一时,个人建议代码这么修改更符合Java API规范也避免线程死循环问题【后面章节会介绍】。

public class ThreadVariableStopDemo {
    public static void main(String[] args) throws InterruptedException {
        VariableStopThread thread = new VariableStopThread("thread_1");
        thread.start();
        Thread.sleep(10);
        thread.interrupt();
    }
}

class VariableStopThread extends Thread {

    public VariableStopThread(String name) {
        super(name);
    }

    public void run() {
        System.out.println(Thread.currentThread().getName() + ":线程开始运行!");
        while(!isInterrupted()) { 
        }
        System.out.println("我停止了! timer:" + System.currentTimeMillis());
    }

}
  • 使用interrupt方法

public class ThreadInterruptDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new InterruptThread("thread_1");
        thread.start();
        Thread.sleep(1);
        System.out.println(thread.getName() + "线程设置:interrupt");
        thread.interrupt();
    }
}

class InterruptThread extends Thread {

    public InterruptThread(String name{
        super(name);
    }

    @Override
    public void run() 
{
        System.out.println(Thread.currentThread().getName() + "线程开始!");
        for(int i =0; i < 1000; i++) {
            try {
                Thread.sleep(0);
                System.out.println("" + (i + 1));
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!");
                break;
            }
        }
        System.out.println(Thread.currentThread().getName() + "线程结束!");
    }
}

640?wx_fmt=jpeg

图1-5 线程退出

从上图可以看出线程正常退出,但是发现一点循环结构体后面一句打印也打印了,解决这个问题的方案有两个:

  • 异常法

@Override
    public void run() 
{
        System.out.println(Thread.currentThread().getName() + "线程开始!");
        try {
            for(int i = 0; i < 1000; i++) {
                if(Thread.currentThread().interrupted()) {
                    System.out.println(Thread.currentThread().getName() + "线程停止状态!");
                    throw new InterruptedException();
                }
                Thread.sleep(0);
                System.out.println("" + (i + 1));
            }
            System.out.println(Thread.currentThread().getName() + "线程结束!");
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!");
            e.printStackTrace();
        }
    }

640?wx_fmt=jpeg

图1-6 线程退出

代码有两个关键点:

  1. for循环外捕获异常【这是程序的关键点】

  2. 判断设置了interrupted标志则抛出异常。

  • return法

@Override
    public void run() 
{
        System.out.println(Thread.currentThread().getName() + "线程开始!");
        try {
            for(int i = 0; i < 1000; i++) {
                Thread.sleep(0);
                System.out.println("" + (i + 1));
            }
        } catch (InterruptedException e) {
            System.out.println(Thread.currentThread().getName() + "线程捕获异常,退出循环!");
            e.printStackTrace();
            return;
        }
        System.out.println(Thread.currentThread().getName() + "线程结束!");
    }

这个方法相对简单,也比较常用。两种方法结果都一样直接退出不进行后续工作,两种方法依据功能需求选择。

上述两个方法sleep都是0,这里给大家看看沉睡中退出,有一个现象会发生。

640?wx_fmt=jpeg

图1-7 线程退出

从【图1-7 线程退出】可以看出sleep使用interrupt()退出直接进入异常,而且interrupt标志位置为false【记住这点】。

线程优先级

线程优先级范围为1-10,API提供等级分为:低(MIN_PRIORITY = 1),中(NORM_PRIORITY=5),高(MAX_PRIORITY=10)。

线程优先级有以下特点:

  1. 继承特性【线程A中启动线程B,线程B继承了A的优先级】;

  2. 随机性【线程调度的顺序不一定是根据优先级,具有随机性】;

public class ThreadPriorityDemo {
    public static void main(String[] args) {
        Thread thread = new ThreadPriority("thread_1<<<<");
        Thread thread_1 = new ThreadPriority(">>>thread_2");
        thread_1.setPriority(Thread.MIN_PRIORITY); //<设置线程优先级
        thread.setPriority(Thread.MAX_PRIORITY);
        thread_1.start();
        thread.start();
    }
}

class ThreadPriority extends Thread {
    public ThreadPriority(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("" + Thread.currentThread().getName() + ",number:" + i + ",Priority:" + Thread.currentThread().getPriority());
        }
    }
}

640?wx_fmt=jpeg

图1-8 线程优先级

运行的很给力,以下体现了两个问题:①线程运行顺序与代码执行顺序无关。②线程优先级具有随机性,不是优先级高的就先完成。

下面验证线程优先级具有继承性,上面代码修改如下:

public static void main(String[] args) {
        Thread thread = new ThreadPriority("thread_1<<<<");
        Thread thread_1 = new ThreadPriority(">>>thread_2");
//      thread_1.setPriority(Thread.MIN_PRIORITY); //<取消设置线程优先级
        thread.setPriority(Thread.MAX_PRIORITY);
        thread_1.start();
        thread.start();
    }

640?wx_fmt=jpeg

图1-9 线程优先级

从上图可以看出thread_2与main线程优先级一样都是5,原因是main线程中启动了thread_2,thread_2继承了mian线程的优先级。

守护线程

守护线程顾名思义是一个线程守护另一个线程【此线程为非守护线程】,故守护的线程称为守护线程,被守护的线程称为非守护线程。作用是为其他线程运行提供便利服务。

public class DaemonThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new DaemonThread();
        thread.setDaemon(true);
        thread.start();
        System.out.println("" + Thread.currentThread().getName() + "停止运行!" );
    }
}

class DaemonThread extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println("DaemonThread 正在运行!");
        }
    }
}

640?wx_fmt=jpeg

图1-10 守护线程

从上图可以看出,主线程停止DaemonThread线程也相应的停止了,但不是立即停止。

线程让步

线程让步【yield方法】让当前线程释放CPU资源,让其他线程抢占。

public class ThreadYieldDemo {
    public static void main(String[] args) {
        Thread thread = new ThreadYield();
        thread.start();
    }
}
class ThreadYield extends Thread {
    @Override
    public void run() {
        long time_start = System.currentTimeMillis();
        for(int i = 0; i < 500000; i++) {
            Math.random();
//          Thread.yield();
        }
        long time_end = System.currentTimeMillis();
        System.out.println("用时:" + (time_end - time_start));
    }
}

640?wx_fmt=jpeg

图1-11 线程正常耗时.jpg

640?wx_fmt=jpeg

图1-12 线程让步耗时.jpg

从以上两图可以看出,线程的让步操作比不让步耗时长。


总结


本篇主要介绍线程API的基础功能,比较常用的线程创建,线程安全,停止线程。只有掌握这些基础才能更好的服务后面线程知识。


推荐阅读:

教你如何使用Flutter和原生App混合开发

聊一聊Android中的字体适配

一步步带你编译哔哩哔哩ijkPlayer


欢迎关注我的公众号,学习技术或投稿

640.png?

640?wx_fmt=jpeg

长按上图,识别图中二维码即可关注

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值