2021年JAVA面试~线程基础

前言

在这里插入图片描述
这篇主要介绍线程的主要方法及线程状态之间转化,

伙计们可以看看上篇关于线程的介绍:
https://blog.csdn.net/u013351145/article/details/117742624

线程优先级

我们可以通过setPriority()来设置线程的优先级,可选1-10之间的级别范围

	 	public final static int MIN_PRIORITY = 1;
	    public final static int NORM_PRIORITY = 5;
    	public final static int MAX_PRIORITY = 10;
    	
        MyRunnable runnable = new MyRunnable();
        Thread thread = new Thread(runnable);
        // 设置线程优先级
        thread.setPriority(MIN_PRIORITY);
        thread.start();

如果超过这个范围就会IllegalArgumentException()异常。
但是线程虽然可以设置优先级,但是执行的顺序并不是依照优先级

        MyRunnable1 runnable1 = new MyRunnable1();
        MyRunnable2 runnable2 = new MyRunnable2();
        MyRunnable3 runnable3 = new MyRunnable3();
        int i=1;
        while (i<6){
            Thread thread1 = new Thread(runnable1);
            // 设置线程优先级
            thread1.setPriority(1);
            thread1.start();

            Thread thread2 = new Thread(runnable2);
            // 设置线程优先级
            thread2.setPriority(5);
            thread2.start();

            Thread thread3 = new Thread(runnable3);
            // 设置线程优先级
            thread3.setPriority(10);
            thread3.start();
            i++;
        }

public static class MyRunnable1 implements Runnable{
        @Override
        public void run(){
            System.out.println("开启线程1");
        }
    }

    public static class MyRunnable2 implements Runnable{
        @Override
        public void run(){
            System.out.println("开启线程2");
        }
    }

    public static class MyRunnable3 implements Runnable{
        @Override
        public void run(){
            System.out.println("开启线程3");
        }
    }

执行结果:
开启线程2
开启线程3
开启线程3
开启线程1
开启线程2
开启线程1
开启线程3
开启线程2
开启线程1
开启线程2
开启线程3
开启线程2
开启线程3
开启线程1
开启线程1

每次执行结果都不同,但是优先级较高的会大概率先执行,
因为JAVA虚拟机采用抢占式调度模式,

简单来说你到我饭店点了一份10块钱蛋炒饭和别人点一份1W的皇帝炒饭
我都会一视同仁,我主要看谁先找到桌子坐下喊:“靓仔,来一份…”。

在这里插入图片描述
而桌子就是cpu时间分片,这个才是关键,才不是靓仔
在这里插入图片描述

线程状态

线程有六种状态
1.New(新建)
2.Runnable(运行))
3.Blocked(阻塞)
4.Waiting(等待)
5.Timed Waiting(计时等待))
6.Terminated(终止)

在这里插入图片描述
New:线程被创建未启动时的状态
Runnable:你可以认为执行完start()方法后状态为Runnable
Blocked:一般来说没有争抢到monitor锁状态为Blocked
Waiting:进入Waiting状态有多种方式,例如没有设置Timeout的wait方法
Timed Waiting:与Waiting类似,到了等待时间就被系统重新唤醒进入
Terminated:run()方法执行完毕之后,线程正常退出后就会进入停止状态

我们继续看上面的图,其中New和Terminated两种状态除非新建立一个线程不然是无法恢复的。
主要是Runnable、Blocked、Waiting和Timed Waiting之间的转化,

Runnable
执行完start()方法线程就会处于这个状态,
进入下面各种状态的方式

Bocked状态进入退回
Synchronized锁住的代码,无法获取monitor拿到monitor锁
Waiting状态进入退回
执行join()join的线程结束/被中断
执行wait()
执行LockSupport.park()执行LockSupport.unpark()
Timed Waiting状态进入退回
执行join(timeout)join的线程结束/被中断
执行wait(timeout)时间到
执行LockSupport.parkNanos(timeout)执行LockSupport.unpark()
执行LockSupport.parkUntil(timeout)
Terminated状态进入退回
执行完毕
出现异常

Waiting和Timed Waiting

Bocked状态进入退回
notify ()
notifyAll()

进入Bocked状态无法直接退回Waiting,需要先拿到monitor锁后变为Runnable再进入。

线程方法

新接触线程的靓仔可能有点小懵,不过没关系
在这里插入图片描述

start()

作用:开启线程

 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();
        }
    }

代码不长,核心是start0()接着执行run方法会调用JVM_StartThread()方法
再创建一个平台相关的OSThread 实例。
具体的细节可以参考这篇文章
Java创建线程底层细节

stop()(不推荐)

作用:停止当前线程

停止当前线程,但是我们基本不使用这个方法,源码中注解也不推荐使用说无法保证安全性,
通常情况下,我们是不会手动停止一个线程,比如:线程正在写一个文件,这时候执行stop方法停止线程,写入文件是不完整的。
因此我们大多数情况使用interrupt方法停止线程。

 @Deprecated
    public final void stop() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            checkAccess();
            if (this != Thread.currentThread()) {
                security.checkPermission(SecurityConstants.STOP_THREAD_PERMISSION);
            }
        }
        // A zero status value corresponds to "NEW", it can't change to
        // not-NEW because we hold the lock.
        if (threadStatus != 0) {
            resume(); // Wake up thread if it was suspended; no-op otherwise
        }

        // The VM can handle all thread states
        stop0(new ThreadDeath());
    }

interrupt ()

作用:通知当前线程停止

interrupt不同之处在于会通知被停止的线程,而对要被停止的线程来说
可以选择立即停止也可以选择一段时间后停止,当然也可以选择拒绝执行。
因此仅限通知,做不做看我心情,
在这里插入图片描述
当然也不会这么任性,
事实上,Java 希望程序间能够相互通知、相互协作地管理线程,因为如果不了解对方正在做的工作,贸然强制停止线程就可能会造成一些安全的问题

public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();

        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();
    }

join()

作用:插队
执行join的线程会先执行,执行完毕才能继续执行其他线程
主要通过while循环查看线程状态,如果线程存活,调用wait()方法等待。

  public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
	// nanos作用可以理解为加时间
    public final synchronized void join(long millis, int nanos)
    throws InterruptedException {

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        join(millis);
    }

sleep()

作用:按照指定时间休眠

    public static void sleep(long millis, int nanos)
    throws InterruptedException {
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
            millis++;
        }

        sleep(millis);
    }

yield()

作用:让位
yield会释放CPU资源,让优先级更高或者同级的线程先执行
其实sleep的底层也是通过yield实现的

    public static native void yield();

wait()

作用:等待
wait是Object实例方法,必须要在同步方法或者同步块中调用,也就是必须已经获得对象锁。
因为本质就是使用monitor锁实现

	public final void wait() throws InterruptedException {
		wait(0);
	}

sleep、yield和wait三个因为作用比较相似,因此在面试的时候出现的几率比较高。
相同点
1.阻塞线程
2.响应interrupt中断

不同点
1.wair方法需要在synchronsize关键字的保护,而sleep不需要
2.sleep方法中必须要定义一个时间(允许0),而wait允许没有时间
3.wait是object类,sleep是Thread类方法。

notify()

作用:唤醒
notify是Object实例方法,可以唤醒因为执行wati方法而阻塞的线程,
当然如果阻塞的线程很多,那么notify方法会随机唤醒一个。

notifyAll()

作用:全部唤醒
notifyAll也是Object实例方法,可以唤醒全部阻塞的线程,

小结

在这里插入图片描述
线程的操作方法大致了解即可,不必深究代码,
一般而言面试过程中的线程安全、线程池才是重点也是面试官询问的最多的。
最后如果有下面想法的老铁请联系我

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值