------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------
Learning before multithreading, you need to be aware of the following concepts:
process : The process is dynamic and is an executing program. Each process execution has an execution order, which is an execution path, or a control unit.
Threads : Threads are attached to a process and can be understood as a sub-execution path under a process, but no process threads are able to execute independently.
The difference between the two : a process is a heavyweight computer task that needs to be assigned an independent address space and system resources. The internal data and state of different processes are completely independent, so communication or conversion between different processes is a burden, while threads are lightweight tasks, and the system resources required for different threads to execute are uniformly distributed by the process, so different threads of the same process will interact with each other during execution. And the data of the thread itself is usually placed in registers, or in the stack used by the program execution, so the burden of thread switching is much smaller than the process switching.
Single Threaded : If a program executes with only one thread under the process, then this is a single-threaded path.
Multithreading : If a program executes a process in which different threads are performing their respective tasks, then this is multithreading.
Understanding the above concepts, the first problem arises. Why do computers use multithreading to perform tasks? The answer is simple, because the number of tasks performed in multi-threaded unit time is larger than single-threaded, and for computer CPUs, a single thread will undoubtedly result in an extremely wasteful CPU.
So how does a multi-threading work in Java?
1. Unlike most other programming languages, Java has built-in support for multithreaded programming (multithreaded programming).
2, multi-threaded program contains two or more than two concurrent running parts, each of these parts of the program is called a thread. Each thread has a separate execution path, so multithreading is a special form of multitasking.
Multitasking is supported by all modern operating systems. However, there are two distinct types of multitasking: process-based and thread-based.
Process-based: a process is essentially an executing program. So process-based multitasking is characterized by allowing your computer to run two or more programs at the same time. So in a process-based multitasking process, the program is the smallest unit of code that the scheduler Dispatches. For example: We can listen to music while chatting on QQ.
Thread-based: In this multitasking environment, the thread is the smallest execution unit. This means that a program has the ability to perform two or more tasks at the same time. For example: We open a QQ software, can chat with many people at the same time.
Some of the state of a thread and how it transitions between different states:
Threads in Java can be broadly divided into five states:
1. NEW: This refers to the creation of an object of the thread class (or its subclasses) through the New keyword
2. Ready: When a thread is created, the other thread calls its start () method, and the thread enters the ready state. The thread in this state is in a running pool, waiting for the CPU to be used.
3. Run: The thread at this point is the ready thread to get the CPU, and the running state is the state that all the threads want to get.
4, death: The thread in the running state, after executing the run () method, it becomes the dead state.
5, blocking: This state refers to the running state of the thread, for some reason, for example, called the Sleep () method, waiting for the user input and so on to let the current CPU to other threads.
Transitions between different states:
First, Create and run a thread
when the start () method is called, the thread starts executing the code in the Run () method. The thread goes into a running state. You can determine whether a thread is running by using the IsAlive () method of the thread class. When the thread is running, isAlive () returns True, and when IsAlive () returns false, the thread may be in a wait state or it may be in a stopped state.
Second, suspend and wake-up threads
once the thread starts executing the run () method, it will continue until the run () method executes this line friend exit. However, in the course of thread execution, there are two ways to make threads temporarily stop executing. The two methods are suspend () and sleep (). After you use Suspend () to suspend a thread, you can wake the thread through the resume () method. Using sleep () causes the thread to hibernate only after the set time has left the thread in a ready state (after the end of the thread hibernation, the threads do not necessarily execute immediately, but are in a ready state, waiting for the system to dispatch). Although suspend () and resume () can easily cause threads to hang and wake up, these two methods are identified as deprecated tags because using these two methods can cause unexpected things to happen. This indicates that the two methods may be removed in future JDK versions, so try not to use both methods to manipulate threads.
Iii. three ways to terminate a thread:
1, use the exit flag, so that the thread exits normally, that is, when the run () method completes after the thread terminates.
2. Use the Stop () method to forcibly terminate the thread (this method is deprecated because stop () and suspend (), resume () can also have unpredictable results).
3. Use the interrupt () method to break the thread
creation of the thread of J Ava:
First, inherit the thread class
steps: 1. Define Class inheritance thread 2. The run () method of the replication thread class 3. Create object 4 of the new definition class, call the start () method to start the thread
Code implementation:
1 PackageCome.file;2 3 //1. Define the Testthread class to inherit the thread class4 classTestthreadextendsthread{5 //2. The run () method of the replication thread class6 Public voidrun () {7System.out.println ("This Is Testthread class");8 }9 }Ten Public classmythread{ One Public Static voidMain (string[] args) { A //to create a newly defined object for the Testthread class -Testthread T =NewTestthread (); - //call the Start () method the T.start (); - } -}
Second, realize runnable interface
Step: 1, create the class implementation runnable interface 2, the replication Run () Method 3, call the new thread (runnable) to create thread 4, call the Start () method to start the thread
Code implementation:
1 PackageCome.file;2 3 //1. Create class to implement Runnable interface4 classTestThread2ImplementsRunnable {5 //2. Replication Run () method6 Public voidrun () {7System.out.println ("This Is TestThread2 class");8 }9 }Ten Public classMyThread2 { One Public Static voidMain (string[] args) { A //3. Call the new thread (runnable) to create Threads -Thread t2 =NewThread (NewTestThread2 ()); - //4. Call the Start () method to start the thread the T2.start (); - } -}
Attention:
1, in the way of inheriting thread, you can use the GetName () method to get the name of the current thread, because there is this method in the thread class. However, in the implementation of Runnable mode, but can not use This.getname (), because the Runnable interface does not have this method (can be seen, because we do not have a hint that we need to rewrite this method), So the current thread object can only be obtained by using the thread's static method Thread.CurrentThread (), in the call to the GetName () method, to get the name of the current threading.
2. For Java, the run () method has nothing special. Like the main () method, it is just a new thread that knows the method name of the call. Therefore, it is legal to raise the Run method on runnable or thread. But does not start a new thread. The new thread is started only if the start () method is called.
Final: Comparison Summary
By comparing the two ways, we can find that the Runnable interface is better than inheriting the thread class way. Because the former implements the interface and can inherit other classes, and in this case, multiple threads share a runnable target object, which is ideal for multiple identical threads to handle the same resource, so that the CPU, code, and data can be separated to form a clear model. A better embodiment of the object-oriented thinking.
Dark Horse programmer--java Basic---multithreading