Talk about Thread class and its common methods in detail

Posted by guest on Wed, 29 Dec 2021 21:07:32 +0100

Thread class is a class used by the jvm to manage threads. In other words, each thread has a unique thread object associated with it.

1.1 common methods of thread class

//Simple example
Thread t1=new Thread();
    Thread t2=new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println();
        }
    });
    Thread t3=new Thread("My name");
    Thread t4=new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("hello");
        }
    },"My name");

1.2 common properties of thread

id: the unique id of the thread. Different threads are different
Status indicates the status of the current thread, which will be described in detail later
Theoretically, threads with high priority are easier to schedule
Background thread we need to know that the Jvm will not end until all non background threads of a process end
Whether the method is alive or not is simply understood, that is, whether the run () method is finished

Note: in the source code, we can see that the default priority of the newly created thread is 5
public static final MAX_Priority=10
public static final MIN_Priority=1
The value of priority is 1-10. The larger the value, the higher the execution weight. However, it is also related to cpu scheduling. It is not absolutely based on priority and will be a little eccentric.

public class demo extends Thread {
    public static void main(String[] args) {
        Thread thread=new Thread(()->{
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "I am Alive");
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                   System.out.println(Thread.currentThread().getName() + "I'm dying");
        });
        System.out.println(Thread.currentThread().getName()+":id:"+thread.getId());//id
        System.out.println(Thread.currentThread().getName()+"name:"+thread.getName());//name
        System.out.println(Thread.currentThread().getName()+"state:"+thread.getState());//state
        System.out.println(Thread.currentThread().getName()+"priority:"+thread.getPriority());//priority
        System.out.println(Thread.currentThread().getName() + "Background thread:" + thread.isDaemon());//Background thread
        System.out.println(Thread.currentThread().getName() + "Alive:" + thread.isAlive());//Is it alive
        System.out.println(Thread.currentThread().getName() + "Is it interrupted:" + thread.isInterrupted());
        thread.start();
        while (thread.isAlive()){
            System.out.println(Thread.currentThread().getName() + "state:" + thread.getState());
        }
    }
}

We can observe these properties through the operation of the above code

1.3 start a thread - start()

I have previously written several methods of how to create threads. I create a thread object by overriding the run method, but the creation of a thread object does not mean that the thread starts running.
We need to know:

  • Overriding the run method is an instruction list that provides the thread with things to do
  • The thread object can be regarded as calling Zhang San and Li Si
  • Calling the start () method is to shout "start dry!" and the thread can really execute independently

The difference between the start() and run() methods

Interview question: it must be noted that the run method is different from the start method. The start method must be called to start the thread.
The difference between start() and run()

1.4 interrupt a thread

Back to the above example, if the boss suddenly calls and says that the other party of the transfer is a liar and needs to stop the transfer quickly, how should Zhang San inform Li Si to stop? This involves our way of stopping threads.
At present, there are two common methods:

  • Through shared Tags
  • Call the interrupt() method to notify
//Mode 1
public class ThreadDemo {
    private static class MyRunnable implements Runnable {
        public volatile boolean isQuit = false;
        @Override
        public void run() {
            while (!isQuit) {
                System.out.println(Thread.currentThread().getName()
                        + ": Leave me alone. I'm transferring money");
                try {
                    Thread.sleep(1000);
               } catch (InterruptedException e) {
                    e.printStackTrace();
               }
           }
            System.out.println(Thread.currentThread().getName()
                    + ": Ah! Almost missed the big event");
       }
   }
    public static void main(String[] args) throws InterruptedException {
        MyRunnable target = new MyRunnable();
        Thread thread = new Thread(target, "Li Si");
        System.out.println(Thread.currentThread().getName()
                + ": Let Li Si start the transfer.");
        thread.start();
        Thread.sleep(10 * 1000);
        System.out.println(Thread.currentThread().getName()
                + ": The boss called. We have to inform Li Si that the other party is a liar!");
        target.isQuit = true;
   }
}
//Mode 2
public class Thread2 {
    private static class MyRunnable implements Runnable {
        @Override
        public void run() {
            // Both methods can be used
            while (!Thread.interrupted()) {
            //while (!Thread.currentThread().isInterrupted()) {
                System.out.println(Thread.currentThread().getName()
                        + ": Leave me alone. I'm busy transferring money!");
                try {
                    Thread.sleep(1000);
               } catch (InterruptedException e) {
                    e.printStackTrace();
                    System.out.println(Thread.currentThread().getName()
                            + ": There's an insider, stop the deal!");
                    break;
               }
           }
            System.out.println(Thread.currentThread().getName()
                    + ": Ah! Almost missed the big event");
       }
   }
    public static void main(String[] args) throws InterruptedException {
        MyRunnable target = new MyRunnable();
        Thread thread = new Thread(target, "Li Si");
        System.out.println(Thread.currentThread().getName()
                + ": Let Li Si start the transfer.");
        thread.start();
        Thread.sleep(10 * 1000);
        System.out.println(Thread.currentThread().getName()
                + ": The boss called. We have to inform Li Si that the other party is a liar!");
        thread.interrupt();
   }
}

This is a much more interesting content, and the old fellow iron is interested in digging it out.

1.5 wait for a thread - join()

Sometimes, we need to wait for a thread to finish its work before we can carry out our next work. For example, Zhang San decides whether to save money only after Li Si's transfer is successful. At this time, we need a method to explicitly wait for the end of the thread.

public class Thread2 {
    public static void main(String[] args) throws InterruptedException {
        Runnable target = () -> {
            for (int i = 0; i < 10; i++) {
                try {
                    System.out.println(Thread.currentThread().getName() 
                                       + ": I'm still working!");
                    Thread.sleep(1000);
               } catch (InterruptedException e) {
                    e.printStackTrace();
               }
           }
            System.out.println(Thread.currentThread().getName() + ": I'm over!");
       };
        Thread thread1 = new Thread(target, "Li Si");
        Thread thread2 = new Thread(target, "Wang Wu");
        System.out.println("Let Li Si start working first");
        thread1.start();
        thread1.join();
        System.out.println("Li Si finished his work and let Wang Wu start his work");
        thread2.start();
        thread2.join();
        System.out.println("Wang Wu's work is over");
   }
}

We can see what happens when we comment out the two join () methods in the code:
Obviously, with luck, we can see the role of the join method in this comparison.

1.6 get the current thread reference

Very familiar

public class ThreadDemo {
    public static void main(String[] args) {
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName());
   }
}

1.7 hibernate current thread

Because thread scheduling is uncontrollable, this method can only ensure that the actual sleep time is greater than or equal to the sleep time set by the parameter.

public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        System.out.println(System.currentTimeMillis());
        Thread.sleep(3 * 1000);
        System.out.println(System.currentTimeMillis());
   }
}

Sleep mode: 1; Thread.sleep (millis:1000) / / sleep for 1s
2.TimeUnit.SECONDS.sleep(timeout:1) / / recommended when the time is long
3.Thread.sleep(TimeUnit.SECONDS.toMillis(duration:1));

Topics: Java Back-end Multithreading