Java Multithreading Summary One: Two ways to create a thread and compare the pros and cons

Source: Internet
Author: User

1. By implementing Runnable interface thread creation

(1). Define a class to implement the Runnable interface, overriding the run () method in the interface. Add specific task code or processing logic to the run () method.

(2). Create an object of the Runnable interface implementation class.

(3). To create an object of the thread class, you need to encapsulate the object of the preceding Runnable interface implementation class. (Interfaces can implement multiple inheritance)

(4). Call the Start () method of the thread object to start the thread

Example code:

[Java]View Plaincopy
  1. <span style="FONT-SIZE:16PX;"  > Packagedemo.thread;
  2. Public class TreadDemo1 implements Runnable {
  3. private int countdown = 10;
  4. @Override
  5. //define tasks in the Run method
  6. public Void Run () {
  7. While (countdown--> 0) {
  8. System.out.println ("#" + Thread.CurrentThread (). GetName () + "("
  9. + Countdown + ")");
  10. }
  11. }
  12. public static void Main (string[] args) {
  13. ///Runnable The Run method is an empty method and does not produce any thread behavior, you must explicitly attach a task to the thread
  14. TreadDemo1 tt=New TreadDemo1 ();
  15. new Thread (TT). Start ();
  16. new Thread (TT). Start ();
  17. System.out.println ("Countdown before rocket launch:");
  18. }
  19. }
  20. </span>


Operation Result:

Countdown before rocket launch:
#Thread-1 (8)
#Thread-1 (7)
#Thread-1 (6)
#Thread-1 (5)
#Thread-1 (4)
#Thread-1 (3)
#Thread-1 (2)
#Thread-1 (1)
#Thread-1 (0)
#Thread-0 (9)

2. Create a thread by inheriting the thread class

(1). First define a class to inherit the thread parent class, overriding the run () method in the parent class. Add specific task code or processing logic to the run () method.
(2). Create an object of the ThreadDemo2 class directly, or you can take advantage of polymorphism, where the variable is declared as the type of the parent class.

(3). Call the Start method, thread T starts, implicitly calls the run () method.

Example code:

[Java]View Plaincopy
  1. <span style="FONT-SIZE:16PX;"  > Packagedemo.thread;
  2. Public class ThreadDemo2 extends Thread {
  3. private int countdown = 10;
  4. @Override
  5. //define tasks in the Run method
  6. public Void Run () {
  7. While (countdown--> 0) {
  8. System.out.println ("#" + This.getname () + "(" + Countdown + ")");
  9. }
  10. }
  11. public static void Main (string[] args) {
  12. new ThreadDemo2 (). Start ();
  13. new ThreadDemo2 (). Start ();
  14. //Because the Start method returns quickly, the main thread can perform other operations, at which time two separate threads are running concurrently
  15. System.out.println ("Countdown before rocket launch:");
  16. }
  17. }
  18. </span>


Operation Result:

#Thread-0 (9)
#Thread-0 (8)
#Thread-0 (7)
#Thread-0 (6)
#Thread-0 (5)
#Thread-0 (4)
#Thread-0 (3)
#Thread-0 (2)
#Thread-0 (1)
#Thread-0 (0)
Countdown before rocket launch:
#Thread-1 (9)
#Thread-1 (8)
#Thread-1 (7)
#Thread-1 (6)
#Thread-1 (5)
#Thread-1 (4)
#Thread-1 (3)
#Thread-1 (2)
#Thread-1 (1)
#Thread-1 (0)
3. Comparison of two methods

The first analysis of the output of the two methods, the same is the creation of two threads, why the results are different?

Creating a thread using the implement Runnable interface can share the same target object (TreadDemo1 tt=new TreadDemo1 ()), implementing multiple identical threads to process the same resource.

Then look at an explanation from the JDK:

RunnableInterfaces should be implemented by classes that intend to execute their instances through a thread. The class must define a run parameterless method called.

This interface is designed to provide a common protocol for objects that want to execute code at the time of the activity. For example, the Thread class implements the Runnable . Activation means that a thread has started and has not stopped.

Additionally, Runnable classes that are not Thread subclasses are provided with an activation method. By instantiating an Thread instance and running itself as a target, you can run the implemented Runnable class without having to create Thread subclasses. In most cases, you should use an interface if you only want to override the run() method without overriding other Thread methods Runnable . This is important because unless the programmer intends to modify or enhance the basic behavior of the class, you should not create subclasses for that class.

Inherited thread classes are used:
(1) Advantages: Write simple, if you need to access the current thread, without using the Thread.CurrentThread () method, use this directly, you can get the current thread.
(2) Cons: Because the thread class has inherited the thread class, it is no longer possible to inherit other parent classes.
Implement the Runnable interface method:
(1) Advantages: The threading class simply implements the Runable interface and can inherit other classes. In this way, multiple threads can share the same target object, so it is very suitable for multiple identical threads to handle the same resource, so that the CPU code and data can be separated to form a clear model, which is a good embodiment of object-oriented thinking.
(2) Cons: Programming is slightly more complex, if you need access to the current thread, you must use the Thread.CurrentThread () method.

Java Multithreading Summary One: Two ways to create a thread and compare the pros and cons

Related Article

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.