一文深入理解java中的线程

深入理解java中的线程

我们知道,一个线程可以用来执行一个任务,并且该任务的执行是异步的,并不会阻塞后面的代码。在一个java进程中,包含main方法的类也是在一个线程中执行的。在实际应用中,如果需要处理一个比较耗时的操作,为了不影响程序整体的响应,通常会将这个耗时的操作封装到一个线程中,异步的执行。但是,线程是怎样实现任务的异步执行的呢?本文将深入了解Thread类,以期望得出线程执行的秘密。

根据《深入理解JAVA虚拟机》中关于线程的章节,我们得知,在java中一个Thread对应着操作系统中的一个线程。而操作系统的线程是稀缺资源,不能无限制的创建线程,这也就是为什么要使用线程池的原因之一。

我们也知道,在java中要实现一个线程,有两种方式:

  • 继承Thread类
  • 实现Runnable接口

但是不管是哪种方式,最后线程的执行还是要通过调用Thread的start()方法

让我们看一下Thread类的重要属性和方法:

// target就是一个传递给Thread等待Thread执行的Runnable对象
/* What will be run. */
private Runnable target;

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

// 类方法,该方法会在Thread类初始化时,在类的构造器<clinit>中被调用,且只会调用一次,该方法主要的作用是注册一些本地的方法,以便后期可以使用
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
    registerNatives();
}
// 注册了以下本地方法:
public static native Thread currentThread();
public static nativevoid yield();
public static native void sleep(long millis) throws InterruptedException;
private native void start0();
private native boolean isInterrupted(boolean ClearInterrupted);
public final native boolean isAlive();
public static native boolean holdsLock(Object obj);
private native static StackTraceElement[][] dumpThreads(Thread[] threads);
private native static Thread[] getThreads();
private native void setPriority0(int newPriority);
private native void stop0(Object o);
private native void suspend0();
private native void resume0();
private native void interrupt0();
private native void setNativeName(String name);
复制代码

让我们看看下面这段代码将输出什么内容:

public static class MyThread extends Thread{
    @Override
    public void run(){
        System.out.println("MyThread---1");
    }
}
public static class MyRunnable implements Runnable{
    @Override
    public void run() {
        System.out.println("MyRunnable---1");
    }
}
public static void main(String[] args) {
    Thread t1 = new MyThread();
    Thread t2 = new Thread(new MyRunnable());
    t1.start();
    t2.start();
    System.out.println("MyThread---2");
    System.out.println("MyRunnable---2");
}
复制代码

该代码的输出内容是不确定的,可能输出为:

MyThread---2
MyRunnable---2
MyRunnable---1
MyThread---1
复制代码

也可能输出为:

MyThread---1
MyRunnable---1
MyThread---2
MyRunnable---2
复制代码

但是如果把上述的代码t1.start(),t2.start()改为:

t1.run();
t2.run();
复制代码

那么输出将变成确定的:

MyThread---1
MyRunnable---1
MyThread---2
MyRunnable---2
复制代码

为什么使用start(),输出的内容是不确定的,而使用run()输出却是确定的呢?这就需要从Thread的启动过程开始了解了。 Thread类中start()方法的源代码如下:

public synchronized void start() {
    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();
复制代码

可以看到,start()方法内部其实调用了一个native的方法start0()。而在Thread类初始化时,执行了一个registerNatives()的方法来注册本地方法,其中start0方法实际关联的是JVM_StartThread方法:

{"start0", "()V",(void *)&JVM_StartThread}
复制代码

在 jvm.cpp 中,有如下代码段:

JVM_ENTRY(void, JVM_StartThread(JNIEnv* env, jobject jthread)){
    ...
    native_thread = new JavaThread(&thread_entry, sz);
    ...
}
复制代码

这里JVMENTRY是一个宏,用来定义JVMStartThread函数,可以看到函数内创建了真正的平台相关的本地线程,其线程函数是thread_entry,如下:

static void thread_entry(JavaThread* thread, TRAPS) {
    HandleMark hm(THREAD);
    Handle obj(THREAD, thread->threadObj());
    JavaValue result(T_VOID);
    JavaCalls::call_virtual(&result,obj,KlassHandle(THREAD,SystemDictionary::Thread_klass()),
    vmSymbolHandles::run_method_name(),    //调用了run_method_name
    vmSymbolHandles::void_method_signature(),THREAD);
}
复制代码

可以看到调用了vmSymbolHandles::runmethodname方法,而runmethodname是在vmSymbols.hpp 用宏定义的:

class vmSymbolHandles: AllStatic {
    ...
    // 这里决定了调用的方法名称是 “run”
    template(run_method_name,"run")
    ...
}
复制代码

从以上的代码中可以看出,Thread执行start()方法,首先会创建一个新的操作系统的线程,然后当该操作线程得到CPU时间片时,会执行一个回调方法:run(),这也就证明了通过start()可以创建一个新线程并异步执行线程体,而通过run()只是执行了一个Thread对象的普通方法而已,并不会并行执行,而是串行执行的。

以下附上一些Thread相关的常见性的问题:

Thread的sleep、join、yield

  • 1.sleep
  1. sleep()使当前线程进入停滞状态(阻塞当前线程),让出CPU的使用,以留一定时间给其他线程执行
  2. sleep休眠时不会释放对象的锁
  • 2.join 在一个线程A中执行了线程B的join方法,则A会挂起,等待B执行完毕后再执行后续任务
public static void main(String[] args){
    Thread t1 = new Thread();
    t1.start();
    t1.join();
    // 以下代码会在t1执行完毕后打印
    System.out.println("t1 finished");
}
复制代码
  • 3.yield
  1. yield并不意味着退出和暂停,只是,告诉线程调度如果有人需要,可以先拿去,我过会再执行,没人需要,我继续执行
  2. 调用yield的时候锁并没有被释放

object的wait、notify、notifyAll

  • 1.wait
  1. wait()方法是Object类里的方法;当一个线程执行到wait()方法时
  2. 该线程就进入到一个和该对象相关的等待池中,同时失去了对象的锁,被唤醒时再次获得锁
  3. wait()使用notify()或者notifyAll()或者指定睡眠时间来唤醒当前等待池中的线程
  4. wait()必须放在synchronized块中,否则会报错"java.lang.IllegalMonitorStateException"
  • 2.notify

wait()和notify()必须操作同一个"对象监视器"

Runnable1 implements Runnable{
    public void run(){
        synchronized(lock){
            // 等待其他线程来唤醒
            lock.wait();
            System.out.println("Runnable1 has been notified by other thread");
        }
    }
}
Runnable2 implements Runnable{
    public void run(){
        synchronized(lock){
            System.out.println("Runnable2 will notify other thread who wait for lock");
            // 唤醒其他线程            lock.notify();
        }
    }
}
public static void main(String[] args){
    Object lock = new Object();
    Thread t1 = new Thread(new Runnable1(lock));
    Thread t2 = new Thread(new Runnable2(lock));
    t1.start();
    t2.start();
}
复制代码

Thread和Runnable的区别

  • Runnable可以通过Thread的start(实际调用了target的run方法)启动,而Thread中target的属性就是一个Runnable
  • Runnable可以实现属性资源共享,Thread不可以实现资源共享
MyRunnable r = new MyRunnable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
// t1/t2线程操作的都是同一个实例r,所以r中的数据可以实现多线程共享
t1.start();
t2.start();
复制代码

线程之间如何进行通信

  • join : 一个线程等待另一个线程执行完毕后再执行
  • wait/notify : 一个线程等待另一个线程唤醒自己所拥有的对象监视器后再执行
  • CountdownLatch : 一个线程等待(countDownLatch.await())其他任意个数的线程执行完毕后(countDownLatch.countDown())再执行
  • CyclicBarrier : 所有线程先各自准备,当所有线程都准备完毕(全部都调用了cyclicBarrier.await())后统一开始执行后续操作
  • Semaphore : 可以控制同时访问的线程个数,通过acquire()获取一个许可,如果没有就等待,而release()释放一个许可
  • Callable : 子线程将执行结果返回给父线程
FutureTask<Integer> futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
Object result = futureTask.get();
复制代码
  1. CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同:
  2. CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行;
  3. CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行;
  4. 另外,CountDownLatch是不能够重用的,而CyclicBarrier是可以重用的。
  5. Semaphore其实和锁有点类似,它一般用于控制对某组资源的访问权限。

线程池的原理

线程池有两个参数:核心线程数coreNum和最大线程数maxNum

假设初始化一个线程池,核心线程数是5,最大线程数是10,线程池初始化的时候,里面是没有线程的

当来了一个任务时,就初始化了一个线程,如果再来一个任务,再初始化了一个线程,连续初始化了5个线程之后,如果第6个任务过来了

这时会把第6个任务放到阻塞队列中

现在线程池中有了5个线程,如果其中一个线程空闲了,就会从阻塞队列中获取第6个任务,进行执行

如果线程池的5个线程都在running状态,那么任务就先保存在阻塞队列中

如果队列满了,并且我们设置了最大线程数是10,但线程池中只有5个线程,这时会新建一个线程去执行不能保存到阻塞队列的任务,此时线程池中有了6个线程

如果线程池中的线程数达到10个了,并且阻塞队列也满了,则可以通过自定义的reject函数去处理这些任务

最后运行一段时间之后,阻塞队列中的任务也执行完了,线程池中超过核心线程数的线程会在空闲一段时间内自动回收

猜你喜欢

转载自juejin.im/post/5e144acaf265da5d381d114f