Common Operating Methods of Java Threads

Introducer

At the beginning, multithreading development is very important, so it is necessary to understand the common operation methods of threads and use multithreading more conveniently. In fact, the sleep() method is enough.

primary coverage

  • Common methods of thread operation

concrete content

Multithreading has many method definitions, but most of them are defined in the Thread class, emphasizing several methods related to our development.

Naming and Acquisition of Threads

The execution of all threaded programs is different each time, because it will preempt resources according to its own situation, so if you want to distinguish each thread, you must rely on the name of the thread. In general, the name of a thread is defined before it starts. It is not recommended to change the name of a thread that has been started or to set a rename for different threads.

If you want to operate on thread names, you can use the following method of the Thread class:

  • Construction method: public Thread (Runable target, String name).
  • Set the name: public final void setName(String name).
  • Get the name: public final String getName().

There is a problem with the operation of thread names. These methods belong to the Thread class, but if you switch back to the Runnable subclass, there is no inheritance of the Thread class, so if you want to get the thread name, you can get the thread name that is currently executing this method. So there's a method in the Thread class:

  • Gets the current thread object: public static void Thread current Thread ().

Example: Observing the naming of threads

class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

public class TestDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        new Thread(mt).start();
        new Thread(mt).start();
        new Thread(mt).start();
    }
}

Output results:

Thread-0
Thread-1
Thread-2

If the Thread class object is not named when it is instantiated, the numbering will be automatically named, that is to say, the name of the thread object will not be repeated.

Example: Modify the code setting name

public class TestDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        new Thread(mt, "My own thread A").start();
        new Thread(mt).start();
        new Thread(mt", My own thread B").start();
    }
}

JDK 1.8 output results:

My own thread A
Thread-0
 My own thread B

Example: Modifying code

public class TestDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        new Thread(mt, "My own thread A").start();
        mt.run();  // Call the run() method directly, main
    }
}

Output result

main
 My own thread A

Originally, the main method is a thread, so all threads created on the main method can actually be represented as sub-threads.
From the above code, we can find that thread implementation has always existed (the main method is the main thread), but where is the process going?

public class Test {
    public static void main(String args[]) {
        for(long i = 0; i < 2000000000; i++);
    }
}

Look at the task manager and a java process appears.
Whenever a program class is interpreted using java commands, it is equivalent to launching a new process for the operating system, while main is only a sub-thread on the process.

Question: How many threads do each JVM process start at least?

  • Main thread: the main execution of the program, as well as the starter threads.
  • gc thread: responsible for garbage collection.

Sleeping of threads

The so-called thread dormancy refers to slowing down the execution speed of the thread slightly.
The method of dormancy:

  • public static void sleep(long millis) throws InterruptedException

Example: Observe sleep() method

class MyThread implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10000; i++) {
            try {
                Thread.sleep(1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ",x = " + x);
        }
    }
}

public class TestDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        new Thread(mt, "My own thread A").start();
    }
}

It is found that the speed of the program is slower, because every loop execution has to sleep, so the execution speed is slower.

Modifying code observation

public class TestDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        new Thread(mt, "My own thread A").start();
        new Thread(mt, "My own thread B").start();
        new Thread(mt, "My own thread C").start();
        new Thread(mt, "My own thread D").start();
        new Thread(mt, "My own thread E").start();
    }
}

The output shows that if multiple thread objects are set up during hibernation, all thread objects will go into the run() method together (the so-called "jointly entering" method is actually because the sequence is too short, but actually different), sleep together, and then enter the run() method together.

thread priority

The so-called priority refers to the higher priority, the more likely it is to execute first. In the Thread class, the following two methods are provided for priority operation:

  • Priority setting: public final void setPriority (int new Priority).
  • Get priority: public final int getPriority().

It was found that int data type was used for setting and prioritizing, and there were three kinds of gatherings for this content:

  • Top priority: public static final int MAX_PRIORITY, 10.
  • Medium priority: public static final int NORM_PRIORITY, 5.
  • Minimum priority: public static final int MIN_PRIORITY, 0.

Example: Test priority

class MyThread implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 20; i++) {
            try {
                Thread.sleep(1000);
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + ",x = " + x);
        }
    }
}

public class TestDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        Thread t1 = new Thread(mt, "My own thread object A");
        Thread t2 = new Thread(mt, "My own thread object B");
        Thread t3 = new Thread(mt, "My own thread object C");
        t1.setPriority(Thread.MAX_PRIORITY);
        t1.start();
        t2.start();
        t3.start();
    }
}

Example: What is the priority of the main thread

public class TestDemo {
    public static void main(String args[]) {
        System.out.println(Thread.currentThread().getPriority());
    }
}

Output result

5

The main thread is of medium priority.

summary

  • Thread.currentThread() takes the current thread class object.
  • Thread.sleep() is mainly dormant, feeling dormant together, but in fact there is a sequence.
  • The higher the priority, the more likely the thread object is to execute first.

More content stamps are as follows:

Keywords: Java Android JDK jvm

Added by JDBurnZ on Tue, 21 May 2019 20:38:04 +0300