Multithreading overview

1、 JVM thread dependent

When the JVM is started, a process will be started, which will start a thread. The JVM startup is multi-threaded, because at least two threads are started, the main thread and the garbage collection thread.

2、 Implementation of multithreading

There are two ways to implement multithreading:

1. Inherit thread class

This approach requires overriding the run () method in the thread class

2. Implement runnable interface

Of course, only implementing the interface is the second step. To really execute, you also need to pass the instance to the thread constructor:

It should be noted that calling the run () method directly will not start the thread, but just run the code inside. To really start the thread, you need to call the start () method.

[why is there mode 1 and mode 2? The reason is that Java does not support multiple inheritance (fortunately, it does not support...), if a subclass has inherited a parent class, in order to implement multithreading, it can no longer inherit the thread class. At this time, we can only implement the runnable interface. In addition, we can see from the above code block that we have two thread class instances T1 and T2, so the interface implementation method is suitable for multiple codes of the same program to process the same resource (i.e. string RES), effectively separate the thread from the program code and data.]

3、 Thread scheduling and priority problem

1. Thread scheduling

Java thread scheduling adopts preemptive scheduling. Preemptive scheduling means that the execution time and thread switching of each thread are controlled by the system. System control means that under a certain operation mechanism of the system, each thread may have the same execution time slice, or some threads may have a long execution time slice, Even some threads don't get a time slice of execution. In this mechanism, the blocking of one thread will not lead to the blocking of the whole process.

2. Priority issues

The priority range of Java threads is 1-10, and the default is 5. The priority of threads still cannot guarantee the execution order of threads. However, threads with high priority have a higher probability of obtaining CPU resources, and threads with low priority do not have a chance to execute. If another new thread is opened in a thread, the newly opened thread is called the child thread of the thread, and the initial priority of the child thread is the same as that of the parent thread.

In Java, priority can be set by setpriority (int ARG) and obtained by getpriority ().

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>