Multithreading in Java (i)

Source: Internet
Author: User

We know that we open a program (or run a software) is actually created a process, but the program is a set of static instructions, and the process is running in the system is a collection of instructions, the process is a system of resource allocation and scheduling of an independent unit. Processes are independent, dynamic, and concurrent. Now the operating system are supported concurrency, but in the specific implementation of the details, according to the different hardware and operating system has different strategies, the more commonly used methods are: Common multi-task operation strategy, preemptive multi-tasking strategy.

Threads extend the concept of a process, a thread is the execution unit of a process, the thread is independent in the process, and is a concurrent execution flow that is created when the process is initialized. For most applications there is only one main thread, and we can simultaneously create multiple threads to execute the flow, which is the thread. That is, a thread is part of a process, a process can have multiple threads, and a thread must have a parent process. Threads can have their own stacks, their own counters, their own local variables and so on. Instead of owning system resources, they share all the resources owned by the process with other threads. Threads are used to accomplish tasks that can be shared with other threads, sharing variables in the parent process and parts of the environment, and collaborating with each other to complete the work of the process.

Simply put: A program runs after at least one process, a process can contain more than one thread, but contains at least one thread.

Thread creation and startup:

Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses, and each thread's task is to complete a certain task, actually executing a program flow, and Java uses the Run method to encapsulate the flow of the program. The next two ways to create threads are described.

The first inherits the thread class to create the threading class:

1, defines the subclass of the thread class, and overrides the thread class's Run method, the method body of the Run method represents the task that the thread needs to complete, that is, the thread executes the body.

2. Create an instance of the thread class subclass, that is, create a threading object.

3. Start the thread with the start method of the thread.

Here is a specific example:

/** *  */ PackageCn.wan;/** * @authorAdministrator **/ Public classTesthreadextendsthread{Private inti;  Public voidrun () { for(; i<20;i++) {System.out.println (GetName ()+""+i); }    }    /**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub         for(inti = 0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+""+i); if(i== 20)            {                NewTesthread (). Start (); System.out.println ("Aaaaaaaaaaaaaaaaaaaaaaaaaa"); NewTesthread (). Start (); }        }    }}

When the Java program runs, at least one thread is created, and that is the main thread, and the threads ' execution body of the main course is not determined by the Run method, but is determined by the main method. The method body of the Main method represents the thread's execution body of the main threads.

The second implementation of the Runnable interface creates a threading class

1, define the implementation class of the Runnable interface and override the Run method of the interface, the method body of the Run method is also the thread execution body of the thread.

2. Create an instance of the Runnable implementation class, and use this instance as the target of the thread class to create the thread object. The instance of this thread class is the real thread object.

//    to create an object that implements the Runnable interface, the Secondthread class implements this interface,   New    secondthread ();    New Thread (ST);

Here is a specific example:

 PackageCn.wan; Public classSecondthreadImplementsrunnable{Private inti; @Override/*** The Run method is also the thread's execution body*/     Public voidrun () {//TODO auto-generated Method Stub         for(; i<100;i++)        {            //When the thread class implements the Runnable interface//If you want to get the current thread, you can only use the Tread.currentthread () methodSystem.out.println (Thread.CurrentThread (). GetName () + "" +i); }            }    /**     * @paramargs*/     Public Static voidMain (string[] args) {//TODO auto-generated Method Stub         for(inti = 0;i<100;i++) {System.out.println (Thread.CurrentThread (). GetName ()+""+i); if(i== 20) {Secondthread St=NewSecondthread (); //Create a new thread by using the new Thread (Target,name) method                NewThread (St, "first one"). Start (); System.out.println ("Aaaaaaaaaaaaaaaaaaaaaaaaaa"); NewThread (St, "second one"). Start (); }        }    }}

The main differences between the first and second methods are:

First Kind

Disadvantage: Because the thread class already inherits the thread class, it is no longer possible to inherit the parent class.

Advantage: Writing is simple, if you need to access the current process just use the This keyword. You do not need to use the Thread.CurrentThread method.

The second Kind

Disadvantage: Writing complex, if you need to access the current thread needs to use the Thread.CurrentThread method.

Advantage: The thread class simply inherits the Runnable interface and can inherit other classes as well. Simultaneous multithreading can share the same target object at the same time, so it is ideal for multiple identical threads to handle the same resource.

Multithreading in Java (i)

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.