Java Multithreading in detail

Source: Internet
Author: User
Tags thread class

Threading OverviewThe operating system supports running multiple tasks at the same time, each of which is a program, and each running program is a process. When a program runs, the internal may contain multiple sequential execution flows, and each sequential execution flow is a thread.1. Threads and ProcessesProcess is a system for resource allocation and scheduling of an independent unit, generally speaking, the process consists of the following three characteristics: 1, Independence: The process is a system of independent entities, it can have its own independent resources, each process has its own private address space. A user process does not have direct access to the address space of another process without the process itself permitting. 2, Dynamic: The difference between the process and the program is that the program is just a static set of instructions, and the process is a collection of instructions that are active in the system. The concept of time was added to the process. Processes have their own life cycles and different states, and these concepts are not available in the program. 3, Concurrency: Multiple processes can be executed concurrently on a single processor, and there is no interaction between multiple processes.concurrency and parallelism differences:parallel means that at the same time, multiple instructions are executed simultaneously on multiple processors;concurrency means that only one instruction can be executed at the same time, but multiple process instructions are executed quickly, making it possible for the macro to have the effect of simultaneous execution of multiple processes. A thread is the execution unit of a process and is part of a process that can have multiple threads. Threads can have their own stacks, their own program counters, and their own local variables, but do not own system resources. It can share the parent process's resources with other threads. A thread is run on its own, and it does not know if any other threads exist in the process. The execution of a thread is preemptive, that is, the currently running thread may be suspended at any time so that another thread can run. One thread can create and revoke another thread, which can be executed concurrently between multiple threads in the same process.Advantages of using Multithreading:1. Memory cannot be shared between processes, but it is easy to share memory between threads. 2. The system needs to reallocate system resources for the process when it is created, but the cost of creating threads is much smaller. Therefore, it is more efficient to implement multi-task concurrency than multi-process using multithreading. 3, the Java language built-in multi-threaded feature support, rather than simply as the underlying operating system scheduling, thus simplifying the Java multithreaded programming. 2. Thread creation and startupJava uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses. The role of each thread is to accomplish a certain task, actually executing a program flow (code executed in a sequential order). Java uses the thread execution body to represent this program flow.first, inherit the thread class to create a threading class(1), define a subclass of the thread class, and override the run () method of the class, which represents the task that the thread needs to complete. So the run () method is called the thread execution body. (2), create an instance of the thread subclass, that is, create a thread object. (3), call the Start () method of the thread object to start the thread.Note: When you create a thread class by using a method that inherits the thread class, the instance variables of the thread class cannot be shared between multiple threads. second, implement Runnable interface Create thread class(1), define the implementation class of the Runnable interface, and override the run () method of the interface, and 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 to create the thread object, which is the true thread object.Note: The Runnable object is only used as the thread execution body as the run () method contained in the Target,runnable implementation class of the thread object only. The actual thread object is still the thread instance, except that the thread thread is responsible for executing its target's run () method. (3), call the Start () method of the thread object to start the thread.Compare two ways: by inheriting the thread class to obtain the current threading object is relatively simple, the direct use of this is OK, but by implementing the Runnable interface to obtain the current thread object must use the Thread.CurrentThread () method. Iii. Creating threads using callable and futureThe callable interface provides a call () method that can be used as the thread execution body, but the call () method is more powerful than the run () method. 1. The call () method can have a return value. 2. The call () method can declare an exception to be thrown. JAVA5 provides a future interface to represent the return value of the call () method in the callable interface, and provides a Futuretask implementation class for the future interface, which implements the future interface, and implements the Runnable interface----can be used as the target of the thread class. In the future interface, several public methods are defined to control its associated callable tasks. (1), Boolean cancel (Boolean mayinterruptifrunning): An attempt was made to cancel the callable task associated with the future. (2), V get (): Returns the return value of the call () method in the callable task. Calling this method will cause the program to block and must wait until the child thread finishes to get the return value. (3), V get (Long timeout,timeunit unit): Returns the return value of the call () method in the callable task. This method causes the program to block timeout and the time specified by the unit, and throws a TimeoutException exception if the callable task still has no return value after the specified time. (4), Boolean iscancelled (): Returns True if the callable task is canceled before it is properly completed. (5), Boolean isDone (): Returns True if the callable task is completed.Note: The callable interface has a generic limit, and the generic parameter type in the callable interface is the same as the call () method return value type. To create and start a thread with a return value, proceed as follows: 1. Create an implementation class for the callable interface and implement the call () method, which will act as the thread execution body, and the call () method does not return a value and then creates an instance of the callable implementation class. 2. Use the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object. 3. Use the Futuretask object as the target of the thread object to create and start a new thread. 4. Call the Get () method of the Futuretask object to get the return value after the child thread execution ends.The pros and cons of creating multithreading in a way that implements Runnable, callable interfaces:1, the thread class just implements the Runnable interface or callable interface, and can inherit other classes. 2, in this way, multiple threads can share the same target object, so it is very suitable for multiple same threads to handle the same resource situation, so that the CPU, code and data can be separated to form a clear model, better reflect the idea of object-oriented. The disadvantage is that programming is slightly more complex and you must use the Thread.CurrentThread () method if you need to access the current thread.the pros and cons of multithreading are created by inheriting the thread class:1, the disadvantage is that because the thread class has inherited the thread class, it is no longer possible to inherit other parent classes. 2, the advantage is that the writing is simple, if you want to access the current thread, you do not need to use the Thread.CurrentThread () method, directly use this to get the current thread.Summary: Use the Runnable interface, callable interface to create multi-threaded.

Java Multithreading in detail

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.