1. Processes and Threads
Process: is a program that is being executed. Each process execution has an execution order. The order is an execution path, or a control unit. Thread: is an independent control unit in the process, which is a smaller execution unit than the process.a thread is simply a means of assigning execution time to a single processor,The thread is controlling the execution of the process.
There is at least one thread in a process.
2. What is multithreading?
Multithreading refers to a process that can produce multiple threads during execution, which can exist simultaneously, run concurrently, and a process may contain multiple threads that execute concurrently. For example, Thunder download, you can download multiple tasks, is multithreaded .
3. The first way to create multithreading: Inherits the thread class. (1) Define class inheritance The thread Class (2) override the Run () method in the Thread classPurpose: Store custom code in the Run method to let the thread run。 (3) Call the thread's Start method.This method has two functions: Start a thread, call the Run method
Package Org.lxh.demo9.threaddemo;class MyThread extends Thread { private String name; Public MyThread (String name) //Set property contents by constructing method { this.name =name; } public void Run () { //overwrite the Run () method in the thread class for (int i=0;i<10;i++) { System.out.println (name+) Run, I= "+i);}}} public class ThreadDemo2 {public static void Main (string[] args) { MyThread mt1= new MyThread ("Thread A"); Created a thread MyThread mt2= new MyThread ("Thread B"); Mt1.start (); Start multi-threading and execute the thread's Run method, using Mt1.run (); Only the object invokes the method, and the thread is created and not running. Wait until the Run method is finished and then proceed to the next step. Mt2.start (); Start Multithreading }}
4.sleep () and wait () comparison
For the Sleep () method , we first need to know that the method belongs to the thread class . The Wait () method is part of the object class .
The sleep () method causes the program to pause execution for the specified time, yielding the CPU to the other thread, but his monitoring state remains intact, and when the specified time is up, it automatically resumes its running state.
During the call to the sleep () method, the thread does not release the object lock.
When the Wait () method is called, the thread discards the object lock, enters the waiting lock pool waiting for the object, and the thread only enters the object lock pool when the Notify () method is called for this object.
Gets the object lock into the running state.
Sleep () and wait () comparisons in Java