8-1 basic concepts: program, process and thread
A program is a set of instructions written in a certain language to complete a specific task. It refers to a piece of static code, static object.
A process is an execution process of a program or a running program. It is a dynamic process: it has its own process of emergence, existence and extinction—— life cycle
Such as QQ in operation and MP3 player in operation
Thread, a process can be further refined into a thread, which is an execution path within a program.
1) The program is static and the process is dynamic.
2) As the unit of resource allocation, the system will allocate different memory areas for each process at run time.
3) If a process executes multiple threads in parallel at the same time, it supports multithreading.
4) Thread is the unit of scheduling and execution. Each thread has its own running stack and program counter (pc). The overhead of thread switching is small
5) Multiple threads in a process share the same memory unit / memory address space. They allocate objects from the same heap and can access the same variables and objects. This makes the communication between threads easier and more efficient. However, the shared system resources operated by multiple threads may bring security risks.
Understanding of single core CPU and multi-core CPU
- Single core CPU is actually a fake multithreading, because it can only execute one thread in a time unit. For example: Although there are multiple lanes, there is only one staff member in the toll station charging. Only after charging can it pass through, so the CPU is like a toll collector. If someone doesn't want to pay, the toll collector can "hang" him (hang him until he has figured it out and has the money ready). But because the CPU time unit is very short, I can't feel it. If it is multi-core, it can give better play to the efficiency of multithreading. (today's servers are multi-core)
- A Java application Exe, in fact, there are at least three threads: main() main thread, gc() garbage collection thread and exception handling thread. Of course, if an exception occurs, it will affect the main thread.
- Parallelism and Concurrency:
Parallel: multiple CPU s execute multiple tasks at the same time. For example: many people do different things at the same time.
Concurrency: one CPU (using time slice) executes multiple tasks at the same time. For example: second kill, multiple people do the same thing.
Advantages of using multithreading
- Background: taking a single core CPU as an example, using a single thread to complete multiple tasks successively (calling multiple methods) must take less time than using multiple threads. Why do you still need multiple threads?
- Advantages of multithreaded programs:
Improve application response. It is more meaningful to the graphical interface and can enhance the user experience.
Improve the utilization of computer system CPU
Improve program structure. The long and complex process is divided into multiple threads and run independently, which is conducive to understanding and modification
When do I need multithreading
1. The program needs to perform two or more tasks at the same time.
2. When the program needs to realize some tasks that need to wait, such as user input, file reading and writing operation, network operation, search, etc.
3. When you need some programs running in the background.
8-2 creation and use of threads
- Thread creation and startup
The JVM of the Java language allows programs to run multiple threads through Java Lang. thread class. - Characteristics of Thread class
1) Each Thread completes its operation through the run() method of a specific Thread object. The body of the run() method is often called the Thread body.
2) Start the Thread through the start() method of the Thread object instead of calling run()
- Thread class constructor
Thread(): create a new thread object
Thread(String threadname): create a thread and specify the thread instance name
Thread(Runnable target): Specifies the target object to create the thread, which implements the run method in the Runnable interface.
Thread(Runnable target, String name): creates a new thread object.
- There are two ways to create threads in the API
JDK1. There are two ways to create a new execution thread before 5:
How to inherit the Thread class
How to implement Runnable interface
- Method 1: inherit Thread class
- Define subclasses that inherit the Thread class.
- Override the run method in the Thread class in the subclass.
- Create a Thread subclass object, that is, create a Thread object.
- Call the thread object start method: start the thread and call the run method.
- Multithreading creation routine, method 1: inherit from Thread class
package atguigu.java; /* * The creation of multithreading, method 1: inherit from the Thread class * 1. Create a subclass that inherits from the Thread class * 2. Override run() -- > of Thread class to declare the operation performed by this Thread in run() * 3. An object that creates a subclass of the Thread class * 4. start() is called through this object * <p> * Example: traverse all even numbers within 100 */ //1. Create a subclass inherited from Thread class class MyThread extends Thread { //2. Override run() of Thread class @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 == 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } } public class ThreadTest { public static void main(String[] args) { //3. Create objects of subclasses of Thread class MyThread t1 = new MyThread(); //4. Call start() through this object: ① start the current thread ② call run() of the current thread t1.start(); //Problem 1: we can't start a thread by calling run() directly. // t1.run(); //Problem 2: start another thread and traverse the even number within 100. You can't let the thread that has started () execute. IllegalThreadStateException will be reported // t1.start(); //We need to recreate a thread object MyThread t2 = new MyThread(); t2.start(); //The following operations are still performed in the main thread. for (int i = 0; i < 100; i++) { if(i % 2 == 0){ System.out.println(Thread.currentThread().getName() + ":" + i + "***********main()************"); } } } }
- Method 1 practice supplement:
package atguigu.exer; /* * Exercise: create two sub threads, one of which traverses an even number within 100 and the other traverses an odd number within 100 */ public class ThreadDemo { public static void main(String[] args) { //Mode 1: // MyThread1 m1 = new MyThread1(); // MyThread2 m2 = new MyThread2(); // m1.start(); // m2.start(); //Method 2: create an anonymous subclass of Thread class new Thread(){ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 == 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } }.start(); new Thread(){ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 != 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } }.start(); } } class MyThread1 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 == 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } } class MyThread2 extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 != 0){ System.out.println(Thread.currentThread().getName() + ":" + i); } } } }
Common methods in testing Thread:
package atguigu.java; /* * Common methods in testing Thread: * 1. start():Start the current thread; Call the run() of the current thread * 2. run(): You usually need to override this method in the Thread class and declare the operation to be performed by the created Thread in this method * 3. currentThread():Static method, which returns the thread executing the current code * 4. getName():Gets the name of the current thread * 5. setName():Sets the name of the current thread * 6. yield():Release the execution authority of the current cpu * 7. join():In thread a, call join() of thread b. At this point, thread a will enter the blocking state until thread b is fully executed, and then thread a will be. * End the blocking state. * 8. stop():Obsolete. When this method is executed, the current thread is forced to end. * 9. sleep(long millitime):Causes the current thread to "sleep" for the specified millitime milliseconds. Within the specified millitime milliseconds, the current * The thread is blocked. * 10. isAlive():Determine whether the current thread is alive * Thread priority: * 1. * MAX_PRIORITY: 10 * MIN _PRIORITY: 1 * NORM_PRIORITY: 5 -->Default Priority * 2.How to get and set the priority of the current thread: * getPriority():Gets the priority of the thread * setPriority(int p):Set thread priority * * Note: the high priority thread should seize the execution right of the low priority thread cpu. But only in terms of probability, high priority threads have high probability * Executed. This does not mean that only after the high priority thread is executed, the low priority thread will execute. */ class HelloThread extends Thread{ @Override public void run() { for (int i = 0; i < 100; i++) { if(i % 2 == 0){ // try { // sleep(10); // } catch (InterruptedException e) { // e.printStackTrace(); // } System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i); } // if(i % 20 == 0){ // yield(); // } } } public HelloThread(String name){ super(name); } } public class ThreadMethodTest { public static void main(String[] args) { HelloThread h1 = new HelloThread("Thread: 1"); // h1.setName("thread one"); //Set the priority of threads h1.setPriority(Thread.MAX_PRIORITY); h1.start(); //Name the main thread Thread.currentThread().setName("Main thread"); Thread.currentThread().setPriority(Thread.MIN_PRIORITY); for (int i = 0; i < 100; i++) { if(i % 2 == 0){ System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i); } // if(i == 20){ // try { // h1.join(); // } catch (InterruptedException e) { // e.printStackTrace(); // } // } } // System.out.println(h1.isAlive()); } }
- Method 2: implement Runnable interface
- Define subclasses and implement Runnable interface.
- Override the run method in the Runnable interface in the subclass.
- Create a Thread object through the Thread class argument constructor.
- Pass the subclass object of Runnable interface as the actual parameter to the constructor of Thread class.
- Call the start method of Thread class: start the Thread and call the run method of Runnable subclass interface.