preface

It was written yesterday:

  • Multiple threads can get through a door in three minutes!

If you haven’t read it, please read it first

Before writing the article, I read through the concurrent chapter of Java Core Technology Volume 1 and the previous part of Java Concurrent Programming Practice, and reviewed the notes I had written before. From today to enter the knowledge of multithreading

In fact, I am also equivalent to learning multi-threading from scratch, if the article is wrong, please also include more, don’t be afraid to point out in the comments area ~~

Thread API

Declare that JDK1.8 is used for this article

Realizing multithreading is essentially operated by Thread class ~ let’s take a look at some important knowledge points of Thread class. The Thread class is too large to look at in its entirety, except for a few common and important methods.

The top of the notes we have been resolved, if you do not know the students can go to: multi-threaded three minutes can enter a door!

1.1 Setting a thread name

When using multiple threads, it is easy to view the Thread name by calling Thread.currentThread().getName().

If we don’t set anything, we’ll see that the name of the Thread looks something like this: The main Thread is called main, and the other threads are thread-x

Here’s how it’s named:

The nextThreadNum() method implementation looks like this:

Based on the number of threads initialized

Click in and see the init method to make sure:

As you can see here, if we want to give a name to a thread, that’s easy. Thread gives us the constructor!

Let’s test it out:

  • Implement a Runnable way to implement multithreading:

public class MyThread implements Runnable {
    
    @Override
    public void run(a) {
		// Prints the name of the current threadSystem.out.println(Thread.currentThread().getName()); }}Copy the code

Testing:


public class MyThreadDemo {
    public static void main(String[] args) {


        MyThread myThread = new MyThread();

        // The parameter constructor gives the thread a name
        Thread thread1 = new Thread(myThread, "Java3y");
        Thread thread2 = new Thread(myThread, "Qq group: 742919422");


        thread1.start();
        thread2.start();
		
		Print the name of the current threadSystem.out.println(Thread.currentThread().getName()); }}Copy the code

Results:

Of course, we can also change the name of the thread by setName(String name). Let’s look at method implementation;

Check whether permissions are modified:

As for the threadStatus attribute, I don’t see where it will change:

1.2 Daemon Threads

Daemon threads serve other threads

  • The garbage collector thread is the daemon thread ~

Daemon threads have one feature:

  • When another user thread finishes executing, the virtual machine exits and the daemon thread is stopped.
  • In other words, the daemon thread is a service thread and there is no need to continue running without a service object

Something to be aware of when using threads

  1. Before the thread startsSet to daemon thread bysetDaemon(boolean on)
  2. Do not access shared resources (databases, files, etc.) using daemons, because it may hang up at any time.
  3. A new thread created in a daemon thread is also a daemon thread

Test a wave:


public class MyThreadDemo {
    public static void main(String[] args) {


        MyThread myThread = new MyThread();

        // The parameter constructor gives the thread a name
        Thread thread1 = new Thread(myThread, "Java3y");
        Thread thread2 = new Thread(myThread, "Qq group: 742919422");

        // Set to daemon thread
        thread2.setDaemon(true); thread1.start(); thread2.start(); System.out.println(Thread.currentThread().getName()); }}Copy the code

When thread 1 and main thread are finished executing, our daemon thread will stop executing

How it works: This is why we set up the daemon thread before startup.

1.3 Priority threads

A high thread priority simply means that the thread has a high chance of acquiring CPU time slices, but this is not a definite factor!

The priority of a thread is highly dependent on the operating system, as is the case with Windows and Linux (where priority is ignored)

As you can see, Java provides a default priority of 5, with a minimum of 1 and a maximum of 10:

Implementation:

SetPriority0 is a native (navite) method:


 private native void setPriority0(int newPriority);

Copy the code

1.4 Thread life cycle

As mentioned in the previous article, threads have three basic states: executing, ready, and blocking

In Java, we have this diagram. Many of the methods on Thread are used to switch the state of the Thread. This part is important.

In fact, the diagram above is incomplete, leaving something out. I’ll redraw a ~ when I talk about thread states later

Here are some methods related to the thread lifecycle

1.4.1 sleep method

Calling the sleep method puts you in a timed wait state, and when the time is up, you’re in a ready state instead of a running state!

As a result, our graph can be added like this:

1.4.2 yield method

Calling the yield method lets another thread execute first, but it is not guaranteed to actually yield

  • I’m free. I’ll let you do it first, if you can

As a result, our graph can be added like this:

1.4.3 the join method

Calling the JOIN method waits for this thread to complete before executing another thread ~

Let’s go in and see the implementation:

The wait method is defined on Object as a native method, so it is unreadable:

The wait method is actually a type of timed wait (with a time parameter). , so we can add our graph:

1.4.3 interrupt method

Thread interrupts had the stop method in previous versions, but it was made obsolete. There is no way to force a thread to terminate!

Because the stop method can cause one thread A to terminate another thread B

  • Terminated thread B immediately releases the lock, which may leave the object in an inconsistent state.
  • Thread A does not know when thread B can be terminated. If thread B is still running the computation phase, thread A calls stop to terminate thread B

In short, the Stop method is so violent and unsafe that it is outdated.

We typically use interrupts to request the termination of threads ~

  • Note that an interrupt does not actually stop a thread, it merely signals the thread that it should be terminated (this is important to understand!).
  • In other words, the Java designer actually wants the thread to terminate itself, and from the above signals, it can decide what business to process.
  • It is up to the notified thread to decide whether to interrupt or continue

Thread t1 = new Thread( new Runnable(){
    public void run(a){
        // If no interruption occurs, the task is executed normally
        while(! Thread.currentThread.isInterrupted()){// Normal task code......
        }
        // Interrupt handling code......
        doSomething();
    }
} ).start();

Copy the code

Again: Calling interrupt() doesn’t actually kill the current thread, it just sets an interrupt flag. This break flag gives us a sense of when to do something! It’s up to us to decide when to interrupt, so we can safely terminate the thread!

Let’s take a look at the source code:

Let’s see what the exception is:

So the interrupt method doesn’t affect the state of the thread at all, it just sets a flag bit

There are two other methods (to check if the thread is interrupted) :

  • The static method interrupted()–> clears the interrupt flag
  • The example method isInterrupted()–> does not clear the interrupt flag bit

As mentioned above, if the blocking thread calls the interrupt() method, an exception is thrown, the flag bit is set to false, and the thread exits the block. Let’s test a wave:



public class Main {
    / * * *@param args
     */
    public static void main(String[] args) {
        Main main = new Main();

        // Create a thread and start it
        Thread t = new Thread(main.runnable);
        System.out.println("This is main ");
        t.start();

        try {

            // Sleep for 3 seconds on the main thread
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            System.out.println("In main");
            e.printStackTrace();
        }

        // Set the interrupt
        t.interrupt();
    }

    Runnable runnable = () -> {
        int i = 0;
        try {
            while (i < 1000) {

                // Sleep for half a second before we execute
                Thread.sleep(500); System.out.println(i++); }}catch (InterruptedException e) {


            // Check whether the blocked thread is still there
            System.out.println(Thread.currentThread().isAlive());

            // Determine the state of the thread's interrupt flag bit
            System.out.println(Thread.currentThread().isInterrupted());

            System.out.println("In Runnable"); e.printStackTrace(); }}; }Copy the code

Results:

Let’s analyze how it is executed:

April 18, 2018 20:32:15(Wow, this method really took me a long time)….. Thanks for the advice of @start de trace ~~~~~

For this reference:

  • www.cnblogs.com/w-wfy/p/641…
  • www.cnblogs.com/carmanlonel…
  • www.zhihu.com/question/41…
  • www.zhihu.com/question/41…

Second, the summary

It can be found that our graph is not complete ~ we will continue to use the above graph when talking about synchronization in the future articles. What’s important in Thread is that there are a few ways to switch Thread states and understand what interrupts really mean.

Using threads can lead to data insecurity and even application failure, which will be discussed later

Before learning the operating system according to the “Computer operating system – Tang Xiaodan” this book also made a little note, are relatively simple knowledge points. It might be helpful

  • Operating system 1 [Introduction]
  • Operating System Part 2 [Process Management]
  • Operating System Part 3 threads
  • Operating system chapter 4 [Processor scheduling]
  • Operating System Chapter 5 [Deadlock]
  • Operating System Chapter 6 [Memory Management]
  • Operating System Part 7 Device Management

References:

  • Java Core Technology Volume 1
  • Java Concurrent Programming
  • Computer Operating System – Dennis Tang

If the article has the wrong place welcome to correct, everybody exchanges with each other. Students who are used to reading technical articles on wechat and want to get more Java resources can follow the wechat public account :Java3y.

Open source project (6 K STAR) :Github.com/ZhongFuChen…

If you want to follow my updated articles and shared dry goods in real time, you can search Java3y on wechat.

The content of the PDF document is typed by hand. If you don’t understand anything, you can ask me directly (the official account has my contact information).