Most basic knowledge of thread

Java multi-threading series chapter 5.

What is the thread

Imagine no thread of the program is kind of how? Baidu network disk when uploading files will not download files, download the files have to wait to file upload is complete. This we now looks against humanity, because we are accustomed to a program can be run simultaneously multiple functions, which are thread credit.

Previous article Know the process of the mentioned, in order to achieve parallel execution of multiple programs, the process of introducing the concept. Now the introduction of the thread is to allow a program to execute concurrently.

Composed of threads

Thread ID : thread identifier.

The current instruction pointer (PC) : point instruction to be executed.

Register set : a set of registers storing unit.

Stack : temporary storage of data and address breakpoints and generally used to protect the site.

Difference between threads and processes

The difference between threads and processes, I think we can use this example to see the difference between the two, the process is a house, a house inhabited by three people, who lived in the house the thread of people. Process is a separate entity with its own resources, the thread is in the process where multiple threads share the resources of the process.

Thread State

We see inside the Java source code, enumeration thread state has the following six.

public enum State {

 //新建状态
 NEW,

 //运行状态
 RUNNABLE,

 //阻塞状态
 BLOCKED,

 //等待状态
 WAITING,

 //等待状态(区别在于这个有等待的时间)
 TIMED_WAITING,

 //终止状态
 TERMINATED;
}

The following six states to 11 to do next explained.

NEW : New state. Before you create the Thread, not execution start (), the thread has been the state NEW. It can be said at this time there is no real map with a thread, just an object.

RUNNABLE : running. After calling thread object start (), entered RUNNABLE state, which illustrate the existence of a real thread in the JVM.

BLOCKED : blocking state. Threads wait for a lock release, which is waiting to acquire a monitor lock.

The WAITING : wait state. When the thread of this state will not be assigned CPU, display and needs to be woken up, otherwise it will wait forever.

TIMED_WAITING : Timeout wait state. The same thread of this state will not be assigned CPU, but it will not wait indefinitely, there is a time limit, the time comes to stop waiting.

TERMINATED : termination status. The end of the thread execution is completed, but this does not mean that the object has not, the object may still exist, but the thread does not exist.

Since there are so many threads state, it must have a state machine, that is, under what circumstances would become A state B state. Here's a brief description of it.

In conjunction with the following figure, when we have a new thread class, that is NEW, calling the start () method, to enter the RUNNABLEstate, then if the trigger wait, then enter the WAITINGstate, if the trigger timeout waiting, then enter the TIMED_WAITINGstate, when the need to synchronize access when the resource, only one thread can access other threads to enter the BLOCKEDstate, when the thread is executed, enter the TERMINATEDstate.

Photos from the network, delete invasion

In fact, in the JVM thread is nine states, as shown below, interested students can understand it.

javaClasses.hpp
enum ThreadStatus {
    NEW = 0,
    RUNNABLE = JVMTI_THREAD_STATE_ALIVE + // runnable / running
                               JVMTI_THREAD_STATE_RUNNABLE,
    SLEEPING = JVMTI_THREAD_STATE_ALIVE + // Thread.sleep()
                               JVMTI_THREAD_STATE_WAITING +
                               JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT +
                               JVMTI_THREAD_STATE_SLEEPING,
    IN_OBJECT_WAIT = JVMTI_THREAD_STATE_ALIVE + // Object.wait()
                               JVMTI_THREAD_STATE_WAITING +
                               JVMTI_THREAD_STATE_WAITING_INDEFINITELY +
                               JVMTI_THREAD_STATE_IN_OBJECT_WAIT,
    IN_OBJECT_WAIT_TIMED = JVMTI_THREAD_STATE_ALIVE + // Object.wait(long)
                               JVMTI_THREAD_STATE_WAITING +
                               JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT +
                               JVMTI_THREAD_STATE_IN_OBJECT_WAIT,
    PARKED = JVMTI_THREAD_STATE_ALIVE + // LockSupport.park()
                               JVMTI_THREAD_STATE_WAITING +
                               JVMTI_THREAD_STATE_WAITING_INDEFINITELY +
                               JVMTI_THREAD_STATE_PARKED,
    PARKED_TIMED = JVMTI_THREAD_STATE_ALIVE + // LockSupport.park(long)
                               JVMTI_THREAD_STATE_WAITING +
                               JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT +
                               JVMTI_THREAD_STATE_PARKED,
    BLOCKED_ON_MONITOR_ENTER = JVMTI_THREAD_STATE_ALIVE + // (re-)entering a synchronization block
                               JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER,
    TERMINATED = JVMTI_THREAD_STATE_TERMINATED
};

Java thread implementation

Here to talk about how to create a thread in Java. As we all know, implementation of the Java threads in two ways: inheritance Thread class and implement Runnable.

Thread class inheritance

Inheritance Thread class, override the run()method.

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("MyThread");
    }

}

Implement Runnable

Implement Runnable, implement run()methods.

class MyRunnable implements Runnable {

    public void run() {
        System.out.println("MyRunnable");
    }

}

这 2 种线程的启动方式也不一样。MyThread 是一个线程类,所以可以直接 new 出一个对象出来,接着调用 start() 方法来启动线程;而 MyRunnable 只是一个普通的类,需要 new 出线程基类 Thread 对象,将 MyRunnable 对象传进去。

下面是启动线程的方式。

public class ThreadImpl {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread myRunnable = new Thread(new MyRunnable());
        System.out.println("main Thread begin");
        myThread.start();
        myRunnable.start();
        System.out.println("main Thread end");
    }

}

打印结果如下:

main Thread begin
main Thread end
MyThread
MyRunnable

看这结果,不像咱们之前的串行执行依次打印,主线程不会等待子线程执行完。

敲重点:不能直接调用 run(),直接调用 run() 不会创建线程,而是主线程直接执行 run() 的内容,相当于执行普通函数。这时就是串行执行的。看下面代码。

public class ThreadImpl {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        Thread myRunnable = new Thread(new MyRunnable());
        System.out.println("main Thread begin");
        myThread.run();
        myRunnable.run();
        System.out.println("main Thread end");
    }

}

打印结果:

main Thread begin
MyThread
MyRunnable
main Thread end

从结果看出只是串行的,但看不出没有线程,我们看下面例子来验证直接调用 run() 方法没有创建新的线程,使用 VisualVM 工具来观察线程情况。

我们对代码做一下修改,加上 Thread.sleep(1000000) 让它睡眠一段时间,这样方便用工具查看线程情况。

调用 run() 的代码:

public class ThreadImpl {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.setName("MyThread");
        Thread myRunnable = new Thread(new MyRunnable());
        myRunnable.setName("MyRunnable");
        System.out.println("main Thread begin");
        myThread.run();
        myRunnable.run();
        System.out.println("main Thread end");
        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("MyThread");
        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

class MyRunnable implements Runnable {

    public void run() {
        System.out.println("MyRunnable");
        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

运行结果:

main Thread begin
MyThread

只打印出 2 句日志,观察线程时也只看到 main 线程,没有看到 MyThreadMyRunnable 线程,印证了上面咱们说的:直接调用 run() 方法,没有创建线程

下面我们来看看有
调用 start() 的代码:

public class ThreadImpl {

    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.setName("MyThread");
        Thread myRunnable = new Thread(new MyRunnable());
        myRunnable.setName("MyRunnable");
        System.out.println("main Thread begin");
        myThread.start();
        myRunnable.start();
        System.out.println("main Thread end");
        try {
            Thread.sleep(1000000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}

运行结果:

main Thread begin
main Thread end
MyThread
MyRunnable

All logs are printed out, and through VisualVM can see the tools MyThreadand MyRunnablethread. Saw this result, remember to create a thread to invoke start()methods.

First we talked about this today, continue to focus on the content of the latter.

推荐阅读

Most basic knowledge of thread

The boss told you not to clog up

Eating fast food can learn serial, parallel, concurrent

A cup of tea, a school with asynchronous learn

Process Know?

Design Patterns looked forgot, and forgot to look at?

Background reply "design mode" can get "a story of a design pattern" eBook

觉得文章有用帮忙转发&点赞,多谢朋友们!

Lieb Rother

Guess you like

Origin www.cnblogs.com/liebrother/p/11546683.html