Java multithreading (two)-common methods of multithreading

Common methods of multithreading

1. Get and set the thread name

  • In the Thread class, you can get the name of the thread through the getName() method, and set the name of the thread through the setName() method.
  • The name of the thread is generally set before the thread is started, but it is also allowed to set a name for the thread that is already running. Running two Thread objects have the same name, but for clarity, this should be avoided as much as possible.
  • In addition, if the program does not specify a name for the thread, the system will automatically assign a name to the thread.
T t1=new T();
t1.setName("线程A");

Get thread:

Thread.currentThread().getName()

There is a method Thread.currenThread() This method is to get the current thread, which is equivalent to
the function of this keyword.

Here when we set the name for the thread, the thread is the name we set, but when we do not set the name, the thread will automatically create the thread name and start with Thread-0.

  1. Main thread
class R implements Runnable{
	public void run() {
		for(int i=0;i<3;i++) {
			System.out.println(Thread.currentThread().getName()+i);}}}
public class Demo02 {
public static void main(String[] args) {
	R r=new R();
	new Thread(r,"thread-A").start();
	r.run();}}

operation result:
image

Here we call the run() method directly through the thread object, so the output result contains a main thread, which is run by r.run(). Because calling this statement is completed by the main method, that is to say, in fact, the main method itself is also a thread-the main thread.

Question: Since the main method appears in the form of threads, how many threads are started during the Java runtime?

Start at least two. One is the main thread and the other is the GC thread.

  1. Determine whether the thread is started
thread.isAlive()
  1. Forced running of threads

In the operating system, you can use the join() method to force a thread to run. During the forced running of the thread, other threads cannot run and must wait for the completion of the second thread before continuing.

join() method

  1. Thread sleep

Thread sleep can make the thread pause execution

To allow a thread to sleep temporarily in the program, use the Thread.sleep() method directly.

  1. Thread interruption

When a thread is running, another thread can directly interrupt its running state through the interrupt() method.

  1. Thread priority

In the thread operation of Java, all threads will remain in the ready state before running. At this time, if the priority of that thread is high, that thread may be executed first.

Set method thread name.setPrionity (priority)

image
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44762290/article/details/112379382