Java provides three methods to implement multithreading:
L inherit the Thread class
L implement the runnable interface
L use timer and timertask combination
I. inherit the Thread class
1. If a class inherits the Thread class, the class has the capability of multithreading, and the class can be executed in multiple threads. ExampleCodeAs follows:
|
Public class firstthread extends thread {
Public static void main (string [] ARGs) {
// initialization thread
firstthread Ft = New firstthread ();
// start thread
ft. start ();
try {
for ( int I = 0; I <10; ++ I) {
// delay 1 second
thread. sleep (1000);
system. out . println ("Main:" + I);
}< strong> catch (exception E) {}
}
Public void Run () {
try {
for ( int I = 0; I <10; ++ I) {
// delay 1 second
thread. sleep (1000);
system. out . println ("run" + I);
}< strong> catch (exception E) {}
} |
2. The thread code must be written inside the run method or called inside the run method.
3. The thread can appear in the form of a separate class. After a class has the capability of multithreading, you canProgramIn the main method.
4. After the run method in the Custom thread is executed, the custom thread will naturally die. For the system thread, it will end only after the main method is executed and other started threads are completed. After the execution of the system thread ends, the execution of the program will actually end.
5. Do not overwrite the START () method in the thread subclass. If you must overwrite the START () method, call the super. Start () method first.
6. After the run method in the Custom thread is executed, the custom thread will naturally die. Therefore, a thread can only be started once. Otherwise, a java. Lang. illegalthreadstateexception will be thrown.
2. Implement the runnable interface
If a class needs to be multi-threaded, it can also be implemented through the java. Lang. runnable interface. The sample code is as follows:
|
// Myrunnable. Java
Public ClassMyrunnableImplementsRunnable {
Public VoidRun (){
Try{
For(IntI = 0; I <10; I ++ ){
Thread.Sleep(1000 );
System.Out. Println ("Run:" + I );
}
}Catch(Exception e ){}
}
}
// Test. Java
Public ClassTest {
Public Static VoidMain (string [] ARGs ){
Myrunnable mr =NewMyrunnable ();
Thread t =NewThread (MR );
T. Start ();
Try{
For(IntI = 0; I <10; I ++ ){
Thread.Sleep(1000 );
System.Out. Println ("Main:" + I );
}
}Catch(Exception e ){}
}
}
|
Iii. Use timer and timertask combination
1. In this implementation method, the Timer class implements a function similar to an alarm clock, that is, to trigger a thread at a scheduled time or every certain time. The timer class implements a thread, but this thread is used to call other threads. The timertask class is an abstract class that implements the runnable interface, which is capable of multithreading.
2. In this implementation method, the class can obtain the multi-thread capability by inheriting timertask, writing the code that requires multi-thread execution inside the run method, and then starting thread execution through the Timer class.
3. In actual use, a timer can start any number of timertask implementation threads, but there will be blocking between multiple threads. Therefore, if multiple threads need to run independently, it is recommended that a timer start a timertask implementation.
4. The following is the sample code:
|
// Mytimertask. Java
ImportJava. util. timertask;
Public ClassMytimertaskExtendsTimertask {
String S;
PublicMytimertask (string s ){
This. S = s;
}
Public VoidRun (){
Try{
For(IntI = 0; I <10; I ++ ){
Thread.Sleep(1000 );
System.Out. Println (S + I );
}
}Catch(Exception e ){}
}
}
// Test. Java
ImportJava. util. timer;
Public ClassTest {
Public Static VoidMain (string [] ARGs ){
// Create a timer
Timer T =NewTimer ();
// Create timertask
Mytimertask mtt1 =NewMytimertask ("thread 1 :");
// Start the thread
T. Schedule (mtt1, 0 );
}
}
|
5. the startup thread in the Timer class also contains two scheduleatfixedrate methods, which implement precise latency when the thread is started repeatedly.
Iv. thread state conversion
1. java threads have five basic states: new, ready, running, blocked, and dead ), shows the transition relationships between these five states:
2. The blocking status means that the thread stops running temporarily because of some reasons. There are three types:
A) blocked in object's wait pool: When the thread is in the running state, if the wait () method of an object is executed, the Java Virtual Machine will put the thread in the waiting pool of this object.
B) blocked in object's lock pool: When the thread is in the running state and tries to obtain the synchronization lock of an object, if the synchronization lock of this object has been occupied by other threads, the Java Virtual Machine will put this thread in the lock pool of this object.
C) Other blocking states (otherwise blocked): When the current thread executes the sleep () method, or calls the join () method of another thread, or sends an I/O request, it will enter this status.
5. Thread Scheduling
1. the Java Virtual Machine adopts a preemptible scheduling model. Thread Scheduling is not time-based. After multiple threads are started at the same time, it cannot be ensured that each thread obtains an equal CPU time slice in turn.
2. If you want to explicitly give another thread a chance to run, you can take one of the following methods:
A) Adjust the priority of each thread.
B) Let the running thread call the thread. Sleep () method.
C) Let the running thread call the thread. Yield () method.
D) Let the running thread call the join () method of another thread.
3. The setpriority (INT) and getpriority () Methods of the thread class are used to set the priority and read priority respectively. The priority is represented by an integer. The value range is 1 ~ 10. The Thread class has the following three static constants:
A) max_priority: The value is 10, indicating the highest priority.
B) min_priority: The value is 1, indicating the lowest priority.
C) norm_priority: the default priority value is 5.
4. The default priority of the main thread is thread. norm_priority. If thread a creates thread B, thread B and thread a have the same priority.
5. Thread sleep: thread. Sleep () -- when a thread executes the sleep () method during running, it discards the CPU and turns to the blocking state. When the thread stops sleeping, it first enters the ready state. If the thread is interrupted during sleep, an interruptexception exception is returned.
6. thread concession: thread. yield () -- when the thread executes the yield () Static Method of the thread class during running, if other threads with the same priority are in the ready state, then yield () the method puts the currently running threads in the runable pool and enables another thread to run. If there is no runable thread with the same priority, the yield () method does not do anything.
7. the sleep () method and yield () method are both static methods of the thread class, which will cause the currently running thread to discard the CPU and give the running opportunity to other threads. The difference between the two is:
A) The sleep () method will give other threads a running opportunity, regardless of the priority of other threads, so it will give the lower-priority thread a running opportunity; yield () the method only gives the thread with the same or higher priority a chance to run.
B) when the thread executes the sleep (long millis) method, it will go to the blocking state. The parameter millis specifies the sleep time. When the thread executes the yield () method, will go to the ready state.
C) The sleep () method declaration throws an interruptexception exception, while the yield () method does not declare that it throws any exception.
D) The sleep () method has better portability than the yield () method, and cannot rely on the yield () method to improve program concurrency performance.
8. wait for the end of other threads: Join () -- The current thread can call the join () method of another thread. The running thread will go to the blocking state until the end of the other thread, it will resume running.
6. Obtain the reference of the current thread object and other
1. The currentthread () Static Method of the thread class returns the reference of the current thread object.
2. The getname () instance method of the thread class returns the name of the thread.
3. The setname () instance method of the thread class can display and set the thread name.
VII. Background thread
1. A background thread is a thread that provides services for other threads, also known as a daemon thread.
2. Background threads are accompanied by foreground threads. Only when all foreground threads end their lifecycles can background threads end their lifecycles. As long as a foreground thread has not finished running, the background thread will not end its lifecycle.
3. The main thread is the foreground thread by default, and the thread created by the foreground thread is also the foreground thread by default.
4. Call the setdaemon (true) method of the thread class to set a thread as a background thread. The isdaemon () method of the thread class is used to determine whether a thread is a background thread.
5. When using background threads, pay attention to the following points:
A) What the Java Virtual Machine can ensure is that when all background threads are running, the Java Virtual Machine will terminate if the background threads are still running. In addition, whether the background thread must end the lifecycle after the foreground thread depends on the implementation of the Program.
B) The thread can be set to a background thread only before the thread starts (that is, before the START () method is called. If the thread calls the setdaemon () method after it starts, the illegalthreadstateexception will occur.
C) The thread created by the foreground thread is still the foreground thread by default, and the thread created by the background thread is still the background thread by default.
8. Thread Synchronization
1. Atomic operations are completed by a group of related operations, which may manipulate resources shared with other threads. During the execution of atomic operations, a thread must take measures so that other threads cannot manipulate shared resources.
2. to ensure that each thread can perform atomic operations normally, Java introduces a synchronization mechanism. The specific method is to add the synchronized mark before the code representing atomic operations. Such code is called a synchronization code block.
3. Each Java object has only one synchronization lock. At any time, only one thread can own the lock.
A) if the lock has been occupied by other threads, the Java Virtual Machine will put the thread in the lock pool of the object, and the thread enters the blocking state. There may be many threads waiting for the lock in the lock pool of the object. When other threads release the lock, the Java Virtual Machine will randomly remove a thread from the lock pool so that the thread has the lock, and go to the ready state.
B) if the lock is not occupied by other threads, the thread will get the lock and start to execute the synchronization code block. In general, the thread will release the lock only after the synchronization code block is executed.
4. If all the code in a method belongs to the synchronous code, you can directly modify it with synchronized before the method.
5. When a thread executes the synchronization code block of an object, other threads can still execute the non-synchronous code block of the object.
6. You can also use the synchronized modifier before static methods.
7. when a thread starts to execute the synchronous code block, it does not mean that it must be run in a non-interrupted manner. The thread that enters the synchronous code block can also execute the thread. sleep () or execute thread. yield () method. At this time, it does not release the lock, but only gives the running opportunity (CPU) to other threads.
8. The synchronized statement will not be inherited.
9. In the following cases, the lock will be released by the thread holding the lock:
A) the lock is released after the synchronization code block is executed.
B) when a synchronization code block is executed, the thread is terminated due to an exception, and the lock is released.
C) when the synchronization code block is executed, the wait () method of the object to which the lock belongs is executed, and the thread will consciously release the lock and enter the waiting pool of the object.
10. In addition to the above cases, the lock will not be released as long as the thread holding the lock has not executed the synchronization code block. Therefore, the thread will not release the lock in the following circumstances:
A) during the execution of the synchronization code block, the thread. Sleep () method is executed. The current thread abandons the CPU and starts sleep. The lock will not be released during sleep.
B) The thread. Yield () method is executed during the execution of the synchronization code block. The current thread releases the CPU but does not release the lock.
C) during the execution of the synchronization code block, other threads execute the suspend () method of the current thread object. The current thread is paused, but the lock is not released. The suspend () method of the thread class has been deprecated.
11. A general rule of thumb to avoid deadlocks is: when several threads need to access Shared resources A, B, and C, ensure that each thread accesses them in the same order, for example, access a first and then access B and C.
9. Thread Communication
1. the java. Lang. object class provides two methods for thread communication:
A) Wait (): the thread that executes this method will release the lock of the object. the Java Virtual Machine places the thread in the waiting pool of the object. This thread waits for other threads to wake it up.
B) y (): the thread that executes this method wakes up a thread waiting in the waiting pool of the object. the Java Virtual Machine selects a thread randomly from the waiting pool of the object, convert it to the lock pool of the object. If there is no thread in the waiting pool of the object, the notify () method does nothing.
2. The object class also has a notifyall () method, which transfers all threads in the waiting pool of the object to the lock pool of the object.