One, foreword

Most computer operating systems use tasks and time-sharing design. Multitasking means that multiple programs can be run simultaneously in an operating system. For example, you can listen to music while chatting with QQ, which means that there are multiple independent tasks, each task corresponds to a process, and each process can produce multiple threads.

Process of 1.

Process is a dynamic execution process of the program, which corresponds to a complete process from code loading, execution to completion of execution, and this process is also the process itself from generation, development to extinction. Operating systems manage multiple processes in a computer system at the same time, allowing multiple processes in the computer system to take turns using CPU resources. Process characteristics:

  1. A process is the basic unit of a system running program
  2. Each process has its own memory space, a set of system resources
  3. The internal data and state of each process is completely independent

Thread 2.

Thread is the smallest unit of operation performed in a process. A process can produce multiple threads during its execution and threads must be executed within a process. Thread is an execution unit within the process, which is a sequence control process that can complete an independent task. If multiple threads are run in a process at the same time to complete different work, it is called multithreading. Threads can be divided into core-level threads and users and threads according to the processing level

1. Core machine thread Core level thread is related to the system task, he is responsible for processing multiple threads between different processes. Allow threads in different processes to schedule threads according to the same relative priority scheduling method, so that they work in an orderly manner, can give play to the concurrency advantage of multiple processors, in order to make full use of computer software/hardware resources

2. User-level threads In the development of the program, due to the needs of the program and written threads are user-level threads, the creation, execution and death of these threads are controlled during the writing of the application. User-level thread switching usually occurs between threads in an application, such as the multi-threaded download in Xunlei, which belongs to the user thread

3. Connection and difference between threads and processes 1. A process has at least one thread 2. Resources are allocated to a process, and all threads of the same process share all resources of the process 3. The processor is assigned to threads, that is, threads are really running on the processor

4. Advantages of multi-threading 1. Multi-threaded programs can bring better user experience and avoid computer crash or blank screen caused by slow execution of programs. 2. Multithreading can maximize the efficiency of computer systems, such as thunderbolt multithreading download.

Second, write thread classes

Each program automatically has at least one thread, called the master thread. The main thread is started when the program is loaded into memory. The main method in a Java program is the entry point to the main thread, which is executed first when a Java program runs. In development, user-written threads are generally defined as threads that use a thread other than the main thread. The process usually involves the following four steps

  1. Define a thread and specify what code the thread is supposed to execute, that is, what it is expected to do
  2. Creating a thread object
  3. Starting a thread
  4. Termination of the thread

There are two common ways to define a Thread, namely by inheriting the java.lang.Thread class and the java.lang.Runnable interface

1. Create a Thread using the Thread class

Common methods of Thread class:

methods instructions
void run() The method by which task operations are performed
void start() Causes the thread to start execution
void sleep(long mils) Hibernates the currently executing thread (suspends execution) for the specified number of milliseconds
String getName() Returns the name of the thread
int getPririt() Returns the priority of the thread
void setPriority(int newPoriority) Changes the priority of a thread
Thread.State getState() Returns the state of the thread
boolean is Alive() Tests whether the line is active
void join() Wait for the thread to terminate
void interrupt() Interrupt threads
void yield() Suspends the currently executing thread object and executes the other threads

Inherit the Thread class and override the Thread class run() method when creating a Thread. Where the run method is the thread to execute the operation task method, so the operation code to be executed by the thread should be written in the run method, and by calling the start method to start the thread. Example: Create a Thread by inheriting the Thread class and entering an integer from 1 to 100. Define a class that inherits Thread, overriding the run method, and implementing data output 2 in the run method. Create a thread object 3. Call the start method to start the thread

Public class MyThread extends Thread{// Example: Create a Thread by inheriting the Thread class. Private int count = 0; Public void run(){for (int I = 1; i <=100 ; i++) { System.out.println(i); }}}Copy the code

Starting a thread

package xc.test1; Public class Test {public static void main(String[] args) {MyThread mt = new MyThread(); // Start thread mt.start(); }}Copy the code

2. Create a thread using the Runnable interface

Although Thread is a straightforward way to create threads, it has a disadvantage. If you define a class that already inherits from another class, you cannot inherit from Thread. Creating threads using the Runnable interface solves this problem. The Runnable interface declares a run method (), that is, public void run(). A class can accomplish all the activity of a thread by implementing the Runnable interface and implementing its run() method, which is called the thread body of the object. Any object that implements the Runable interface can be the target object of a thread. Example: Create a Thread by inheriting the Thread class and entering an integer from 1 to 100. MyThread class is defined to implement Runable interface, and Runnable interface to implement the run method, in the run method output data 2. Create a thread object 3. Call the start method to start the thread

Public class MyThread implements Runnable{// Example: Create a Thread by extending the Thread class. Private int count = 0; Public void run(){for (int I = 1; i <=100 ; i++) { System.out.println(i); }}}Copy the code

Start the start

package xc.test1;

public class Test {
    public static void main(String[] args) {
        //实例化线程对象
       Thread thread = new Thread(new MyThread());
        //启动线程
        thread.start();
    }
}

Copy the code

The state of the thread

The thread life cycle has four phases: fresh, runnable, blocked, and dead

1. Freshman status

A thread comes to life before the start method is called. The thread is just an empty object with no resources allocated to it. It can only be started and terminated.

2. Running status

When the thread is started after the start method is called, the system allocates the required resources outside the CPU to the thread and the thread is in a runnable state. Of course, the thread may not be running in this state. For machines with only one CPU, only one runnable thread can occupy the processor at any one time

3. Blocked status

When a running thread cannot continue running for some reason, it enters a blocked state, which is an unrunnable state. The cause of the blocked state

  1. Call Thread’s static method sleep()
  2. When a thread executes an I/O operation, the I/O operation is not complete
  3. If a thread’s execution requires an object lock that is being used by another thread, it will block
  4. A thread enters a blocked state when its suspend() method is called

3. State of death

A thread enters the dead state when its run method finishes running, its stop method is called, or an uncaught exception occurs during the run.

Four, thread scheduling

When multiple runnable threads queue for CPU resources, each thread is automatically assigned the priority of a thread. The priority indicates the importance or urgency of the thread. Runnable threads queue according to their priority. Thread scheduling is based on a “first come, first served” principle based on priority. Thread scheduler preemptive scheduling, that is, if a thread with a higher priority enters the runnable state during the current thread execution, the thread with a higher priority will be scheduled to execute immediately.

1. Thread priority

The priority of a Thread ranges from 1 to 10. 10 indicates the highest priority. The default value is 5. Each Thread has a priority between thread.min_priority and thread.max_priority. The priority of a Thread can be changed using setPrioity(int grade)

2. Implementation of thread scheduling methods

Join () causes the current thread to suspend execution until the calling thread finishes. Public final void Join () public final void Join (long mills) public final void Join (long mills,int nanos)

Example: Use join() to block thread implementation steps: 1. Define thread class, output 5 times the name of the current thread 2. Define a test class that blocks the main thread using the Join method

package xc.test2; public class MyThread extends Thread { public MyThread(String name){ super(name); } public void run(){ for (int i = 0; i <5 ; System.out.println(thread.currentThread ().getName()+""+ I); }}}Copy the code
package xc.test2; Public class Test {public static void main(String[] args) {// MyThread for (int I = 0; i <10 ; i++) { if (i==5){ MyThread t = new MyThread("MyThread"); try { t.start(); t.join(); } catch (InterruptedException e) {e.printStackTrace(); } } System.out.println(Thread.currentThread().getName()+""+i); }}}Copy the code

Example: Blocking a thread with the sleep() method Implementation Steps: Defining a thread blocking a thread with the sleep() method in the run() method defines a test class

package xc.test3; Public class Wait {//== Example: Block thread with sleep() == public static void bySec(long s){for (int I = 0; i < s; I ++) {system.out.println ((I +1)+" second "); } try { Thread.sleep(1000); } catch (InterruptedException e) {e.printStackTrace(); }}}Copy the code
package xc.test3; public class Test { public static void main(String[] args) { System.out.println("wait"); BySec (5); // Make the main thread wait five seconds before executing system.out.println ("start"); }}Copy the code

2. Yield ()

  • public static void yield()

The yield method allows the current thread to suspend execution and allow other threads to execute while still runnable and not blocked. In this case, the system selects another thread with the same or higher priority to execute. If there is no other thread with the same or higher priority, the thread continues to execute.

Example: Using the yield method to suspend a thread implementation steps: 1. Define two threads 2. 3. Define the test class

package xc.test4; public class FirstThread extends Thread{ public void run(){ for (int i = 0; i < 5; I++) {System. Out. Println (" the first thread first "+ (I + 1) +" runs "); Thread.yield(); // Suspend thread}}}Copy the code
package xc.test4; public class SecThread extends Thread{ public void run(){ for (int i = 0; i < 5; I++) {System. Out. Println (" the second thread first "+ (I + 1) +" runs "); Thread.yield(); }}}Copy the code
package xc.test4; public class Test { public static void main(String[] args) { FirstThread f = new FirstThread(); SecThread s = new SecThread(); f.start(); s.start(); }}Copy the code

The difference between sleep and yield methods

Sleep () method The yield () method
Causes the current thread to enter the blocked state Causes the current thread to pause execution
The current thread waits for the specified time even if there are no other threads waiting to run If there are no other threads waiting to execute, the current thread will resume execution immediately
Other threads waiting to execute have an equal chance Threads of the same priority or higher are run
# # the last
Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!