Java Multi thread creation

Source: Internet
Author: User

Long time no More blog, has been busy working on the thing recently. Now finally empty, this 2 days will seize time to tidy up multi-threaded and socket, the javase end off.


What are the first things involved in multi-threading? The first thing to know about threads, why to use threads, what are the advantages of threading, and what are the differences between threads and processes? Once you know the approximate thread content, you should encode it to implement Java multithreading. There are 2 ways to create a thread class and then call the corresponding API to control the thread. Then there is one of the biggest and most important pieces of knowledge, thread synchronization. The previous ones understand the life cycle of the thread, and the actual encoding does not write to those encodings many times, but thread synchronization is often used. It is important to synchronize code blocks, synchronous methods, synchronization locks, and so on. Finally, a thread pool problem, this understanding is good, in the back of the framework of a lot of cache technology using the pool technology, we do not need to encode.


    • Threads and processes
In actual development, especially in the Java EE, basically no project is single-threaded, are multi-threaded. For example, the server processes multiple requests.


    • What is a process?
Almost all operating systems support running multiple tasks at the same time, a task is usually a program, then the running program is called a process. The scheduling of the process is the responsibility of the OS (some systems are exclusive (Windows), some are shared (Unix), and the process has priority based on importance). The time is divided by the OS into a number of time slices. JAVA supports multithreading at the language level. The time allotted is still the OS.
    • What is a thread?
When a program runs, the internal may contain multiple sequential execution flows, so that each sequential execution flow is called a thread.

    • About the relationship between them 2:
After a program runs at least one process, a process can contain multiple threads, but at least one thread is included.
A thread is a resource created and maintained by an operating system, and the JVM is a process for the operating system.
For a single CPU system, only one thread can run at a time. A thread object represents a single threading.
A process is a separate data space, and a thread is a shared data space. The thread object exists in a contiguous address space (static) in the virtual machine process space.

    • Note about threading:
1. Threads are dynamic and are different from thread objects.
2. The thread object differs from other objects in that the thread object is able to apply to manage a thread resource in the bottom layer.
3. Only call the start () method on the thread object is the bottom layer to apply for managing a thread resource.
4. Task concurrency execution is a macro concept, which is a micro-serial.
5. The process will not exit until all threads have finished. When multithreaded programming, do not forget the Java Program Runtime default main thread, the main method of the method body is the main thread of the execution body.

    • There are 2 conceptual differences to note here: parallelism and concurrency.
Parallelism means that at the same time, multiple instructions are executed simultaneously on multiple processors.
Concurrency means that at the same time, only one instruction can be executed. However, multiple instructions are executed quickly, allowing multiple processes to be executed simultaneously at the macro level. In other words, it just seems to be executed at the same time, in fact, the actual implementation is still a piece.


    • Advantages of Multithreading:
1, memory cannot be shared between processes, but it is easy to share memory between threads.
2, the system creation process needs to reallocate system resources for the process, but it is much less expensive to create threads, and multi-tasking is more efficient than multi-process using multithreading.
3,java language built-in multithreading support, rather than simply as the underlying operating system scheduling mode, thus simplifying the Java multithreaded programming


    • Thread creation and startup
A total of 2 ways: 1, inherits the thread Class 2, implements the Runnable interface. The code is as follows:
/** *  * @version 1L * @author linkinpark * @since 2015-2-3 * @motto dream like fireworks heart like water, classmate teenager not romance * @desc ^ inherit thread, rewrite the Run method. */public class MyThread extends thread{private int i = 0;public void run () {for (; I < i++) {//Output I discontinuous, indicating that this method cannot share a system Resource System.out.println (This.getname () + "" + i);}} public static void Main (string[] args) {for (int i = 0; i <; i++) {//outputs the main thread System.out.println (Thread.CurrentThread (). GetName () + "" + i), if (i = = 20) {//start preemption output Here, note I discontinuous new MyThread (). Start (); New MyThread (). Start ();}}}

public class MyThread1 implements runnable{private int i = 0: @Overridepublic void Run () {for (; I < i++) {//Output I continuous, table This way it will share the same system resources//There is no thread here, so only in this way: first return the currently executing thread object, and then get the name System.out.println (Thread.CurrentThread (). GetName () + "" + i);}} public static void Main (string[] args) {for (int i = 0; i <; i++) {//Output main thread System.out.println (Thread.CurrentThread (). g Etname () + "" + i), if (i = =) {MyThread1 myThread1 = new MyThread1 ();//start preemption output Here, note that I continuous new thread (MyThread1, "Lincoln's first Thread") . Start (); New Thread (MyThread1, "Second thread of Lincoln"). Start ();}}}

    • A comparison of these 2 ways to create threads:
First, it is necessary to look at the code of the thread class Run method. The code is as follows:
public void Run () {if (target! = null) {    target.run ();}    }
Here is a target, how to understand this target? The Run method is also called the thread execution body, we can understand this way, the thread is a program flow, this program flow to manipulate an object, then the object of the operation is this target, It is important to note that the Java language thread must use the Run method inside the Runnable object.


The difference between the 2 implementations is as follows:
1, implement the Runnable interface, you can also inherit other classes. Java is a single inheritance ah, if you go directly to inherit the thread class, you can no longer inherit another class.
2, implement the Runnable interface, multiple threads can share the same target object, so it is very suitable for multiple identical threads to process the same resource
3, implement runnable interface, coding a little bit more. Access to the current thread can only use Thread.CurrentThread (), and if you inherit the thread class, you can get the current thread by using this directly.

Java Multi thread creation

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.