Java Multithreading Summary One: Two ways to create threads and compare

Source: Internet
Author: User

1. Thread Concept: Thread is the execution flow from beginning to the beginning of a task, the thread provides a mechanism to run the task, and for Java, a program can concurrently execute multiple threads that can run concurrently on a multiprocessor system. When the program runs as an application, the Java interpreter initiates a thread for the main () method.

2. Parallelism and Concurrency:

(1) Concurrency: In a single-processor system, multiple threads share CPU time, while the operating system is responsible for dispatching and allocating resources to them.

(2) Parallel: In a multiprocessor system, multiple processors can run multiple threads at the same time, which can run concurrently at the same times, but not concurrently, only multiple threads share CPU time and only one thread at a time.

3. Thread creation:

(1) Basic concept: Each task in Java is a running object, in order to create a task, the task class must be defined first, and the task class must implement the Runnable interface. threads, in essence, are objects that facilitate task execution. The execution of a thread is the execution of the run () method in a task class to the end.

(2) Create a thread from the Runnable interface:

A. Define a task class to implement the Runnable interface, implement the Run () method in the Runnable interface (the Run () method tells the system thread how to run it), and define the specific task code or processing logic in the run () method.

B. After defining a task class, create a Task object for the task class.

C. The task must be executed in the thread, creating an object of the tread class, passing the previously created task class object that implements the Runnable interface as a parameter to the constructor of the tread class.

D. Call the Start () method of the tread class object to start a thread. It causes the task's run () method to be executed, and the thread terminates when the run () method finishes executing.

Instance code:

1  PackageCom.muzeet.mutithread;2 3 //Each task is an instance of the Runable interface, the task is a running object, and the thread is an object that facilitates task execution. You must create a task class to override the Run Method definition task4  Public classThreadDemo1ImplementsRunnable {5     Private intCountdown = 10;6 @Override7     //override the Run method to define the task8      Public voidrun () {9          while(countdown-->0)Ten         { OneSYSTEM.OUT.PRINTLN ("$" +Thread.CurrentThread (). GetName () A+ "(" + Countdown + ")"); -         } -     } the     //calling the Start method initiates a thread that causes the Run method in the task to be called, and the Run method finishes executing the thread termination -      -      Public Static voidMain (string[] args) { -Runnable Demo1 =NewThreadDemo1 (); +          -Thread Thread1 =NewThread (demo1); +Thread thread2 =NewThread (demo1); A Thread1.start (); at Thread2.start (); -          -SYSTEM.OUT.PRINTLN ("Rocket Launch countdown:"); -          -          -     } in  -}

Program Run Result:

Rocket launch countdown: $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)

Run two task objects at the same time:

  

 Public Static void Main (string[] args) {        new  ThreadDemo1 ();         New ThreadDemo1 ();         New Thread (demo1);         New Thread (DEMO2);        Thread1.start ();        Thread2.start ();                System.out.println ("Rocket launch countdown:");                    }

Operation Result:

Rocket launch countdown: $Thread -0 (9) $Thread -0 (8) $Thread -0 (7) $Thread -0 (6) $Thread-1 (9) $Thread -0 (5) $Thread-1 (8) $Thread-0 (4) $ Thread-1 (7) $Thread -0 (3) $Thread-1 (6) $Thread-1 (5) $Thread -0 (2) $Thread 1 (4) $Thread-1 (3) $Thread-1 (2) $ Thread-1 (0) $Thread -0 (1) $Thread-0 (0)

  

(3) inherit the thread class to create threads:

A. First create a task class extends thread class, because the thread class implements the Runnable interface, so the custom task class also implements the Runnable interface, re-run () method, which defines the specific task code or processing logic.

B. Create a task class object that can use thread or runnable as the custom variable type.

C. Invoke the Start () method of the custom object to start a thread.

Example code:

1  PackageCom.muzeet.mutithread;2 3 //Each task is an instance of the Runable interface, where the task is a running object, and the thread can run the object. You must create a task class to override the Run Method definition task4  Public classExtendfromthreadextendsThread {5     Private intCountdown = 10;6 @Override7     //override the Run method to define the task8      Public voidrun () {9          while(countdown-->0)Ten         { OneSYSTEM.OUT.PRINTLN ("$" + This. GetName () A+ "(" + Countdown + ")"); -         } -     } the     //calling the Start method initiates a thread that causes the Run method in the task to be called, and the Run method finishes executing the thread termination -      -      Public Static voidMain (string[] args) { -          +Extendfromthread Thread1 =NewExtendfromthread (); -Extendfromthread thread2 =NewExtendfromthread (); + Thread1.start (); A Thread2.start (); at          -SYSTEM.OUT.PRINTLN ("Rocket Launch countdown:"); -          -          -     } -  in}

Operation Result:

Rocket launch countdown: $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) $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)

One thread waits for another thread to finish before executing: When performing printnum this task, print to the number 50 o'clock, instead of printing the character C this task, know that the thread thread4 execution to continue to perform the printing of the digital task.

1  PackageCom.muzeet.testThread;2 3  Public classPrintnumImplementsRunnable {4 5     Private intLastnum;6     7      PublicPrintnum (intN)8     {9Lastnum =N;Ten     } One  A @Override -      Public voidrun () { -         //TODO auto-generated Method Stub theThread thread4 =NewThread (NewPrintchar (' C ', 40)); - Thread4.start (); -         Try { -          for(inti=1;i<=lastnum;i++) +         { -System.out.println ("" +i); +             if(i = = 50) A             { at                  - Thread4.join (); -                  -             } -         } -}Catch(interruptedexception e) { in             //TODO auto-generated Catch block - e.printstacktrace (); to         } +     } -      the}

4. Comparison of two methods (reproduced)

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. When the first thread finishes performing a task, countdown is already 0, so the second thread will not output. Instead of inheriting thread creation threads, new has two task class objects, with individual member variables that do not interfere with one another.

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. 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. (it is recommended to create a task class and implement the Runnable interface instead of inheriting the thread 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 threads and compare

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.