1, Introduction to related concepts
(1) Process: is a program that is being executed. Each process execution has an execution order, which is either an execution path or a control unit. Used to allocate space.
(2) Thread: is a separate control unit in the process, the thread controls the execution of the process, and at least one thread in a process.
When the Java virtual machine starts, there will be a process java.exe, at least one thread in the process is responsible for the execution of the Java program, the thread that runs the code in the main method, so the main method is the main thread. In more detail, the Java virtual machine more than one thread, the main method to start the main thread when there is a garbage collection mechanism, in fact, this is multithreaded. Therefore, the Java Virtual machine is also multithreaded.
2, Thread creation and startup
(1) Inherit thread class to create threads
Steps:
(a) defines a subclass of the thread class.
(b) override the Run () method of the thread class.
(c) Create a thread object.
(d) Call the object's start () method to start the process and invoke the run () method.
classDemoextendsThread//(a) defines a subclass of the thread class. { Public voidRun () {//(b) override the Run () method of the thread class. for(inti = 0; I < 100; i++) {System.out.println (i+ "Demo run!"); } } Public Static voidMain (string[] args) {Demo d=NewDemo ();//(c) Create a thread object. D.start ();//(d) Call the object's start () method to start the process. //Code to test for(inti = 0; I < 100; i++) {System.out.println (i+ "Main run!"); } }}Test results:
You can see that the main thread executes alternately with our custom threads.
Attention:
(a) The thread object created cannot call the run () method. If the call to the run () method is the same as the usual function call, the effect of multithreaded execution is not achieved. Calling the start () method not only opens the thread, but also calls the run () method.
(b) The result of multiple runs of the program is different every time, because many threads are competing for CPU execution, and only one thread is running at a time, and the CPU is doing a quick switchover to achieve the results that appear to be running concurrently. This is a feature of multithreading: Randomness. The number of people who Rob who executes and how long it takes to execute is CPU-determined.
(c) Why should I overwrite the run () method? The Thead class is used to describe a thread, and the run method in that class simply holds the location of the code to be run.
(d) In fact, thread d = new Thread () can create an instance of a thread, but D.start () is the run () method that opens the thread class, which does not have any definitions.
(2) Implement Runnable interface Create thread class
Look at one question first.
//The train station has 16 tickets, need to sell from four windows, if according to the above multi-threaded implementation, the program is as followsclassTicketextendsThread {Private inttick = 16;//Number of tickets--- Public voidrun () { while(true){ if(tick>0){ //print here to see which window is selling which ticket, here simply let the ticket count from 1---System.out.println (Thread.CurrentThread (). GetName () + "... sale:" + tick--); } } } Public Static voidMain (string[] args) {Ticket T1=NewTicket (); Ticket T2=NewTicket (); Ticket T3=NewTicket (); Ticket T4=NewTicket (); T1.start (); T2.start (); T3.start (); T4.start (); }}
As a result, we can see that more than 16 sold, in fact, each window or thread sold 16 tickets, it is intolerable.
There is a method: private int tick = 16; This sentence becomes: private static int tick = 16. However, static is not generally defined because its life cycle is too long.
Formally enter the second method of creating a thread:
//The train station has 16 tickets, need to sell from four windows, if according to the above multi-threaded implementation, the program is as followsclassTicketImplementsRunnable {Private inttick = 16;//Number of tickets--- Public voidrun () { while(true){ if(tick>0){ //print here to see which window is selling which ticket, here simply let the ticket count from 1---System.out.println (Thread.CurrentThread (). GetName () + "... sale:" + tick--); } } } Public Static voidMain (string[] args) {Ticket T=NewTicket (); Thread T1=NewThread (t); Thread T2=NewThread (t); Thread T3=NewThread (t); Thread T4=NewThread (t); T1.start (); T2.start (); T3.start (); T4.start (); }}
From this result we can see that we have achieved our goal. Summary steps:
(a) Define the implementation class for the Runnable interface and override the run () method of the interface.
(b) Create an instance object of the Runnable implementation class, and use this object as the target of the thread class to create the thread class object.
Ticket t = new Ticket (); the object T is not a thread object
Thread T1 = new thread (t), T1 created with object T as argument is the real thread object
(c) Invoke the Thread object T1 method Start () to start multithreading.
You can specify a name for the thread object when it is created.
(3) Common methods
(a) 返回对当前正在执行的线程对象的引用。
public static Thread currentThread()
(b) Returns the name of the thread object.
Public final String GetName()
(4) Precautions
(a) objects inheriting the thread class can use the CurrentThread () method or the This keyword. But the implementation class that implements runnable can only get the current object through the CurrentThread () method.
(b) Multiple threads created by the Runnable interface can share the properties of an instance of a thread class. This makes it ideal for multiple identical threads to work on the same resource. (That is, the example of why this threading method is being sold)
(c) Other classes can also be inherited in a way that is implemented by the Runnable interface. 3, the life cycle of the thread
new : When a program uses the new keyword to create a thread object, the thread is in a new state, and as with other Java objects, the object is only allocated memory for it and initializes its initial value, at which point the object does not show the characteristics of the outgoing path.
Ready : When the new thread object calls the Start () method (Figure 1), the thread is in a ready state, the virtual opportunity creates a method call stack and a program counter for it, and the thread in this state does not start execution, only indicates that it can be executed, and when it is executed, The key to see the scheduler inside the virtual machine scheduling.
Run : When the on-site of the ready state gets the execution of the CPU (2 in the figure) and starts executing the Run method, it indicates that the thread is in a running state.
blocking : It is not possible to keep running when a thread starts running, unless he runs at a very short time and the CPU has not switched on and has run to the end, but this is not the case. In general, the CPU is divided by the time slice many threads in this time is not complete, at this point the thread is running to break, let other threads get execution opportunity. As a result, a running thread goes into a blocking state when the following conditions occur. In fact, the blocking state is a kind of interrupt state of a running thread, it cannot run at this time, but the thread cannot run and there are other states, for example, to return to the ready state, as explained below.
(a) A running thread enters a blocking state
(1) The thread calls the sleep () method to voluntarily discard the consumed processor resources.
(2) The thread calls a blocking Io method that is blocked in the method when it returns to the front thread.
(3) The thread is waiting for a notification.
(4) The thread attempted to obtain a synchronization monitor, but the synchronization monitor was held by another thread.
(5) The program calls the thread's suspend method to suspend the thread. This method easily leads to deadlocks, which are obsolete.
(b) A running thread enters a ready state
(1) does not cause a thread to lose resources through the sleep () method
(2) The yield () method is called to allow the running program to enter a ready state.
(c) The blocking state of the thread into the ready state
(1) The blocking state of the thread can only enter the ready state, not directly into the running state
(2) The call to the sleep () method passes the specified time
(3) The blocking Io method called by the thread has returned
(4) thread successfully obtains a waiting synchronization monitor
(5) The thread waits for a notification, while the other thread sends a notification
(6) A thread that is suspended is called the Resume () method. This method easily leads to deadlocks, which are obsolete.
death : The end of a thread is the state of death.
(1) Normal end thread
(2) The thread throws an uncaught exception or error.
(3) Use the Stop () method of the thread to terminate the thread. Easy to deadlock, obsolete.
Attention:
(a) When a new thread object is created, the thread is in a new state, and if the run () method of the object is called, the thread object is no longer in the new state, and the start () method cannot be called, only the start () method can be called on the thread object in the new state. However, you cannot call the start () method two times on a newly created thread object.
(b) Do not call the start () method on an already dead thread.
(c) There is a way to detect if the thread object is dead. -----the IsAlive () method, when the thread is in new and dead state, the method returns False, and vice versa!
Java Threading Details (i)