(1) Java multithreading: two methods for creating threads: java Multithreading

Source: Internet
Author: User

(1) Java multithreading: two methods for creating threads: java Multithreading
Multithreading

In the single-CPU era, a single task can only execute a single program at a time point, and then the computer can execute multiple or multiple processes in parallel at the same time point in the multi-task stage, although it is not a "same time point" in the true sense, multiple tasks or processes share one CPU, and the operating system will switch the CPU among multiple tasks, in this way, each task has the opportunity to run a certain time slice. As multitasking brings new challenges to software developers, programs cannot assume that they exclusively occupy all CPU time and all memory and other computer resources, A good program role is to release these resources when they no longer use them, so that other programs can use these resources, later, multithreading technology was developed to enable parallel execution of multiple threads in a program. The execution of a thread can be considered as a CPU executing the program. When a program runs in multiple threads, it seems that multiple CPUs are executing the program at the same time. However, the emergence of multi-core CPUs in modern computers means that different threads can be executed in parallel by different CPU cores.

Multithreading brings the following advantages:

1. Faster program response 2. Better resource utilization 3. Simpler Program Design in some cases
Thread creation and startup inherit Thread class override run Method
Public class MyThread extends Thread {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + ": Inheriting the Thread class to create a Thread");} public static void main (String [] args) {thread = new MyThread (); Thread. start ();}}
Implement the Runnable interface to override the run Method
Public class MyRunnable implements Runnable {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + ": implement the Runnable interface to create a Thread");} public static void main (String [] args) {thread Thread = new Thread (new MyRunnable ()); thread. start ();}}

The above two methods can be used to create threads with the same final effect, but most people prefer to use the Runnable interface method. The main reason is that the first method is more in line with the object-oriented idea, the thread is divided into two parts: the thread object and the thread task. The thread pool can effectively manage the threads that implement the Runnable interface, if the Thread pool is full, new threads will wait in queue for execution until the Thread pool is idle, and if the Thread is implemented by implementing the Thread subclass, this will be more complicated; the third Java language is single-inheritance multi-implementation.

Threads improve the thread creation and execution sequence
Public class ThreadExample {public static void main (String [] args) {for (int I = 0; I <5; I ++) {new Thread ("Thread name" + I) {public void run () {System. out. println ("Thread:" + getName () + "running ");}}. start () ;}} Test Result: Thread name 0 runningThread: Thread name 2 runningThread: Thread name 1 runningThread: Thread name 3 runningThread: Thread name 4 running

Although the thread startup sequence is ordered, the execution sequence is not ordered. The thread execution sequence is determined by the JVM and the operating system.

Internal Thread Execution Process Analysis
public class ThreadExample2 {    public static void main(String[] args) {        new Thread(new Runnable() {            public void run() {                try {                    Thread.sleep(500);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("runnable :" + Thread.currentThread().getName());            }        }) {            public void run() {                try {                    Thread.sleep(500);                } catch (InterruptedException e) {                    e.printStackTrace();                }                System.out.println("thread :" + Thread.currentThread().getName());            }        }.start();    }}

The output result of running the above Code is: thread: Thread-0.

Because the Thread's start method eventually calls the Thread's run method, the Code is as follows:

public void run() {    if (target != null) {        target.run();    }}

From the code, we can see that if the target object is not empty, run the run method of the target object (target is to construct the passed Runnable object through new Thread (Runnable target ), however, the run method of the Thread has been rewritten, so the run method in the Runnable instance will not be executed.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.