Java多线程基础

Java多线程

导语:关于无论是线程还是多线程,案例并不少,比如我们经常说的买票机制等,在这里我们先主要介绍线程的状态以及创建线程的方式,对于买票案例在下篇博客将会实例介绍


线程状态转换

我们最常见的线程状态主要有如下几种情况:

  • New(新建):创建线程后但是没有启动
  • Runnable(可运行):可能正在运行,也可能正在等待时间片,包含了操作系统中的Ready(准备未运行,获取cpu 的使用权)和Running(运行中,获得了cpu 时间片)
  • Blocked(阻塞):等待获取一个排它锁,阻塞状态是指线程因为某种原因放弃了cpu 使用权,暂时停止运行
  • Waiting(无限期等待):等待其它线程显式地唤醒,否则不会被分配 CPU 时间片
  • Timed Waiting(限期等待):无需等待其它线程显式地唤醒,在一定时间之后会被系统自动唤醒。调用 Thread.sleep() 方法使线程进入限期等待状态时,常常用“使一个线程睡眠”进行描述。调用 Object.wait() 方法使线程进入限期等待或者无限期等待时,常常用“挂起一个线程”进行描述。睡眠和挂起是用来描述行为,而阻塞和等待用来描述状态。阻塞和等待的区别在于,阻塞是被动的,它是在等待获取一个排它锁。而等待是主动的,通过调用 Thread.sleep() 和 Object.wait() 等方法进入
  • Terminated(死亡):可能是线程结束任务之后自己结束,或者产生了异常而结束

我们还可以通过Thread源码来进行分析
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述


创建线程

通常我们在不使用线程池的情况下,基本可以使用三种方式来创建线程:

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

继承Thread

先列出一段代码:

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

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        System.out.println("结束了......");
    }
}

经过运行你会发现结果是不一定的,有可能先执行“执行了…”,也有可能先执行的是“结束了…”,也就是说运行多线程的时候运行结果与代码顺序是没有多大关系的,因为线程作为子任务存在,CPU不知何时会调用。其实我们不难发现,Thread这个类从根本上来说就是继承了Runnable接口的实现类,我们可以看下Thread这个类的源码如下:

public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private volatile String name;
    private int            priority;
    private Thread         threadQ;
    private long           eetop;

    /* Whether or not to single_step this thread. */
    private boolean     single_step;

    /* Whether or not the thread is a daemon thread. */
    private boolean     daemon = false;

    /* JVM state */
    private boolean     stillborn = false;

    /* What will be run. */
    private Runnable target;

    /* The group of this thread */
    private ThreadGroup group;

    /* The context ClassLoader for this thread */
    private ClassLoader contextClassLoader;

    /* The inherited AccessControlContext of this thread */
    private AccessControlContext inheritedAccessControlContext;
  
        ......

那么问题出现了,同一个线程可以调两次 start() 方法吗?,如下:

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

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.start();
        myThread.start();
        System.out.println("结束了......");
    }
}

运行结果如下:

Exception in thread "main" java.lang.IllegalThreadStateException
 at java.lang.Thread.start(Thread.java:708)
 at MyThread.main(MyThread.java:16)
执行了......

结果为非法线程状态异常,说明同一个线程不能被 start 两次,那么为什么呢?我们点开start() 方法的源码如下:

public synchronized void start() {
    if (threadStatus != 0)
 
     throw new IllegalThreadStateException();
     boolean started = false;
     
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
   
        }
    }
}

通过源码我们不难分析出如果threadStatus 状态不为0的时候他会抛出一个IllegalThreadStateException非法异常,反之状态为0的时候表示一个新的线程

实现Runnable

先展示出代码如下:

public class MyThread implements Runnable{

    @Override
    public void run() {
        System.out.println("执行了......");
    }

    public static void main(String[] args) {
        Runnable runnable = new MyThread();
        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println("结束了......");
    }
}

他的实现原理是什么样的呢,我们点开Runnable源码如下:

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

我们可以看到在Runnable这个借口中,只定义了一个抽象接口方法,所以我们直接实现run()方法即可,但是执行还是需要通过Thread将执行线程加到线程调度器中,这样才能使CPU对其进行调用

实现Callable

Callable代码如下:

public class MyThread implements Callable {

    @Override
    public Object call() throws Exception {
        int i;
        for (i = 0; i < 10; i += 2) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
        return i;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyThread myThread = new MyThread();
        FutureTask<Integer> ft = new FutureTask<>(myThread);
        new Thread(ft, "有返回值的线程").start();
        System.out.println("子线程的返回值" + ft.get());
    }
}

Callable+Future/FutureTask却可以获取多线程运行的结果,可以在等待时间太长没获取到需要的数据的情况下取消该线程的任务

总体来说相对于Runnable来说,Callable可以返回执行结果,是个泛型,和Future、FutureTask配合可以用来获取异步执行的结果;Callable接口的call()方法允许抛出异常;Runnable的run()方法异常只能在内部消化,不能往上继续抛

注:Callalbe接口支持返回执行结果,需要调用FutureTask.get()得到,此方法会阻塞主进程的继续往下执行,如果不调用不会阻塞。


基础线程机制

Executor

Executor 管理多个异步任务的执行,而无需程序员显式地管理线程的生命周期。这里的异步是指多个任务的执行互不干扰,不需要进行同步操作。

Java中有三个比较常用的线程池,分别是FixedThreadPool,SingleThreadExecutor,CachedThreadPool

  • SingleThreadExecutor:这是一个线程数量为1的线程池,所有提交的这个线程池的任务都会按照提交的先后顺序排队执行。单个线程执行有个好处:由于任务之间没有并发执行,因此提交到线程池种的任务之间不会相互干扰。程序执行的结果更具有确定性
  • FixedThreadPool:这是一个线程数固定的线程池,当这个线程池被创建的时候,池里的线程数就已经固定了。当需要运行的线程数量大体上变化不大时,适合使用这种线程池。固定数量还有一个好处,它可以一次性支付高昂的创建线程的开销,之后再使用的时候就不再需要这种开销
  • CachedThreadPool:和缓存有关的线程池,每次有任务提交到线程池的时候,如果池中没有空闲的线程,线程池就会为这个任务创建一个线程,如果有空闲的线程,就会使用已有的空闲线程执行任务。并且这个线程池还有一个销毁机制,如果一个线程60秒之内没有被使用过,这个线程就会被销毁,这样就节省了很多资源。

实现代码如:

public class MyRunnable implements Runnable {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new MyRunnable());
        }
        executorService.shutdown();
    }
    @Override
    public void run() {
        System.out.println("执行了......");
    }
}

执行结果如下:

执行了......
执行了......
执行了......
执行了......
执行了......

Daemon

守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分;当所有非守护线程结束时,程序也就终止,同时会杀死所有守护线程

main() 属于非守护线程,在线程启动之前使用 setDaemon() 方法可以将一个线程设置为守护线程

public static void main(String[] args) {
    Thread thread = new Thread(new MyRunnable());
    thread.setDaemon(true);
}

sleep()

Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec 单位为毫秒;sleep() 可能会抛出 InterruptedException,因为异常不能跨线程传播回 main() 中,因此必须在本地进行处理。线程中抛出的其它异常也同样需要在本地进行处理

public void run() {
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

yield()

对静态方法 Thread.yield() 的调用声明了当前线程已经完成了生命周期中最重要的部分,可以切换给其它线程来执行。该方法只是对线程调度器的一个建议,而且也只是建议具有相同优先级的其它线程可以运行

public void run() {
    Thread.yield();
}

结语:到这基本上对于线程的六种状态、创建方式以及基础线程机制就介绍到这,想学习下多线程案例可点击

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值