Multithreading in Java (1)

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:

 

650) this. width = 650; "onclick = 'window. open (" http://blog.51cto.com/viewpic.php? Refimg = "+ this. src) 'alt =" "border =" 0 "src =" http://www.bkjia.com/uploads/allimg/131228/13555U2T-0.jpg "/>

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.

 

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.