Multithreading in Java

Source: Internet
Author: User

1. Process and thread

A process is a running program. Each process has independent resources and can be executed concurrently on the processor. Multiple processes do not affect each other.
A thread is the execution unit of a process. After a process is initialized, the main thread is created. A thread can have its own stack, counter, and local variables, but the system resources are shared with other threads of its parent process. One thread can create and withdraw another thread. The scheduling and management of the thread itself are completed by the process.

2. Thread creation and startup


There are two ways to create a thread:

2.1 inherit Thread class to create Thread class

The procedure is as follows:
A. Define the subclass of the thread class and override the run () method. The method body of the run () method is the task to be executed by the thread;
B. Create an instance of the thread subclass;
C. Use the START () method of the thread object to start the thread.

 

     
  1. // Create a Thread class by inheriting the Thread class
  2. Public class firstthread extends thread
  3. {
  4. Private int I;
  5. // Override the run method. The method body of the run method is the thread execution body.
  6. Public void run ()
  7. {
  8. For (; I <100; I ++)
  9. {
  10. // When the Thread class inherits the Thread class, you can directly call the getname () method to return the name of the current thread.
  11. // If you want to obtain the current thread, use this directly.
  12. // The getname of the thread object returns the name of the current thread
  13. System. Out. println (getname () + "" + I );
  14. }
  15. }
  16. Public static void main (string [] ARGs)
  17. {
  18. For (INT I = 0; I <100; I ++)
  19. {
  20. // Call the currentthread method of thread to obtain the current thread
  21. System. Out. println (thread. currentthread (). getname () + "" + I );
  22. If (I = 20)
  23. {
  24. // Create and start the first thread
  25. New firstthread (). Start ();
  26. // Create and start the second thread
  27. New firstthread (). Start ();
  28. }
  29. }
  30. }
  31. }

Note that the program has three threads. When I = 20, the other two threads are started. In addition, the two threads cannot share the instance property I, and their input I value is not consecutive.

2.2 implement the runnable interface to create a Thread class

The procedure is as follows:
A. Define the class implemented by the runnable interface and override the run () method;
B. Create an instance and use the instance as the target of the thread class to create a thread object;
C. Execute the START () method of the thread object.

 

     
  1. // Create a Thread class by implementing the runnable interface
  2. Public class secondthread implements runnable
  3. {
  4. Private int I;
  5. // The run method is also the thread execution body.
  6. Public void run ()
  7. {
  8. For (; I <100; I ++)
  9. {
  10. // When the Thread class implements the runnable interface,
  11. // If you want to obtain the current thread, you can only use the thread. currentthread () method.
  12. System. Out. println (thread. currentthread (). getname () + "" + I );
  13. }
  14. }
  15. Public static void main (string [] ARGs)
  16. {
  17. For (INT I = 0; I <100; I ++)
  18. {
  19. System. Out. println (thread. currentthread (). getname () + "" + I );
  20. If (I = 20)
  21. {
  22. Secondthread ST = new secondthread ();
  23. // Use the new thread (target, name) method to create a new thread
  24. New thread (St, "New thread 1"). Start ();
  25. New thread (St, "New thread 2"). Start ();
  26. }
  27. }
  28. }
  29. }

Multiple Threads with the same thread class instance implementing the runnable interface as the target object can share the instance attributes of the thread class. The two threads in the above Code output consecutive I values.

3. Thread Lifecycle

Shows the thread lifecycle:

 

Note the following:

A. when the new keyword is used to create a thread, the thread is in the new State. After the object calls start (), the thread is in the ready state, indicating that the thread can run, the time to run depends on the scheduling of the thread scheduler in the Java Virtual Machine.

B. the startup thread calls the START () method instead of the run () method. Call the START () method to start the thread. The system will treat the run () method as the thread's execution body. Otherwise, it will not be treated as a thread and thus be executed immediately.

C. Other threads have the same status as the main thread and will not end with the end of the main thread. The START () method cannot be called for dead threads.

4. thread control

Below are some common methods for controlling threads:

A. Join

Its function is to make a thread wait for another thread to continue execution after the execution is completed. Call the join () method in the waiting thread in the thread to be waited.

B. Background thread

Background threads run in the background to provide services for other threads. The feature is that if the foreground process dies, it also dies. You can call the setdaemon (true) method of the thread object to set it as a background process. The subthread created by the foreground thread is the foreground thread by default, and the subthread created by the background thread is the background thread by default. To ensure that the setdaemon (true) method is correctly set, it must be called before start.

C. Thread sleep

The sleep method provided by the Thread class can be a specified period of time when the currently executed thread sleep is in a blocking state. It will not be called even if there are no other running threads in the system. CPU resources can be obtained if other threads have no priority requirements.

D. Thread concession yield

The static method yield of the thread class is the ready state of the currently running thread and does not block this thread. It only allows the system thread scheduler to schedule it again.

5. Thread Synchronization

The security problem of multithreading comes from the confusion caused by operations on the same data when different threads are switched. For example, when two threads concurrently modify the same file, exceptions may occur. Java provides the following solutions for thread synchronization:

A. synchronous code block

Java multithreading supports introducing synchronization monitors to solve this problem.

 

     
  1. Synchronized (OBJ) {// OBJ in brackets is the synchronization monitor.
  2.  
  3. ...
  4. // The code here is the synchronization code block
  5. }
  6. // The meaning of the above Code is that the synchronization monitor must be locked before the thread starts to execute the synchronization code block. We recommend that you use shared resources that may be accessed concurrently as synchronization monitors.

In this way, when any resource execution that wants to modify the resource, it is first said that the resource is locked and other processes cannot modify the resource during the lock process, after the modification is complete, the lock on the resource is released. This ensures the security of only one thread in the critical section at the same time.

Note that the synchronization monitor can be used by any object as long as it is unique and constant. It is generally recommended to use shared resources that may be accessed concurrently as the synchronization monitor.

B. Synchronization Method

In Java multithreading, the method modified with the synchronized keyword becomes the synchronization method. For the synchronization method, you do not need to specify the monitor. The object itself is the monitor. When the synchronization method is executed, the synchronization monitor this will be locked first. Synchronized ensures that only one thread can access resources. Therefore, the synchronization method should be defined inside the object class to be exclusively accessed.

C. Synchronous lock

A synchronization lock is another mechanism for thread synchronization. The synchronized lock declared as final is used as the synchronization monitor. The lock is explicitly applied before the method body is executed, and the lock is displayed after the execution, when a lock object is used, each Lock Object corresponds to an accessed object, which is equivalent to the implementation mechanism of the synchronization method and ensures thread synchronization.

 
 

     
  1. Class X {90
  2. // Define the Lock Object
  3. Private Final reentrantlook lock = new reentrantlook ();
  4. //...
  5. // Define the method to ensure thread security
  6. Public void M (){
  7. // Lock
  8. Lock. Lock ();
  9. Try {
  10. // Method body
  11. //.....
  12. } Finally {
  13. // Unlock
  14. Lock. Unlock ();
  15. }
  16. }
  17. }

The above various thread synchronization mechanisms are actually using a constant object as the synchronization monitor. In the synchronization Block Code, although the method is defined inside the Thread class, the accessed object as the synchronization monitor is passed from the external to the internal after initialization, with immutability. In the synchronization method mechanism, the synchronization monitor is the this object. When the object is initialized, the object is already constant, so its synchronization monitor is also unchanged. The lock mechanism is similar to the synchronization method mechanism, except that its monitor is lock, because the lock is also initialized when the exclusive access object is initialized, so it is also constant.

6. Thread Communication

A. mechanism for controlling the coordinated running of threads (1)

Java has three built-in methods for coordinated thread control, which belong to the object class, but must be called using the synchronization monitor.

The wait () method causes the current thread to wait and releases the lock on the synx.

The Y () method is used to wake up a single thread waiting on the synchronization machine and choose any wake-up method.

Y () Wake up all waiting threads.

B. mechanism for controlling the coordinated running of threads (2)

In the program that uses the Lock Object to ensure synchronization, the synchronization monitor is not the this object itself, so the condition object method must be used to ensure synchronization.

 
 

     
  1. // Obtain the Lock Object explicitly
  2. Private final lock = new () reentrantlock ();
  3. // Obtain the condition variable of the specified Lock Object
  4. Private final condition cond = lock. newcondition ();
  5. //.....
  6. Cond. Await ();
  7. //.....
  8. Cond. Signal ();
  9. //.....
  10. Cond. signalall ();

The functions of these three methods are the same as those of the preceding three methods.

C. Use a pipeline stream for communication

Same as the mechanism in the I/O Stream (add this part after I/O learning)

7. Thread Pool

The thread pool creates a large number of threads when the system starts. When the program passes a runnable or callable object to a thread pool, the thread pool starts a thread to execute the run method of the object, after the run method is executed, the thread will not die, but return to the thread pool again to become idle.

 
 

     
  1. // Implement the runnable interface to define a simple
  2. Class testthread implements runnable
  3. {
  4. Public void run ()
  5. {
  6. For (INT I = 0; I <100; I ++)
  7. {
  8. System. Out. println (thread. currentthread (). getname ()
  9. + "The I value is:" + I );
  10. }
  11. }
  12. }
  13.  
  14. Public class threadpooltest
  15. {
  16. Public static void main (string [] ARGs)
  17. {
  18. // Create a thread pool with a fixed number of threads (6)
  19. Executorservice pool = executors. newfixedthreadpool (6 );
  20. // Submit two threads to the thread pool
  21. Pool. Submit (New testthread ());
  22. Pool. Submit (New testthread ());
  23. // Close the thread pool
  24. Pool. Shutdown ();
  25. }
  26. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.