[Major attack] Java beginners to proficient-multithreading (on)

Source: Internet
Author: User
Document directory
  • 1.1 processes and threads
Java multithreading (I) 1 difference between a thread and a process 1.1 difference between a process and a thread

A process is an application running in memory. Each process has its own memory space. A process can have multiple threads. For example, in windows, a running xx.exe is a process.Java program processes include the main thread and garbage collection thread (background thread ).

ThreadIt refers to an execution task (control unit) in a process. A process can run multiple threads, and multiple threads can share data. Multi-process: multiple programs run in the operating system at the same time, multiple tasks run in the same process at the same time; a process has at least one thread, in order to improve efficiency, you can enable multiple control units in a process.

Run concurrently. For example, multi-thread download software.

Multi-thread download: At this time, the thread can be understood as the download channel. One thread is the download channel of an object, and multiple threads are used to download multiple channels at the same time. when the server provides the download service, the downloader shares the bandwidth. When the priorities are the same, the total server evenly allocates the total download threads. It is easy to understand that if you have many threads, the faster you download. Popular download software supports multithreading. You can run the program at the same time, but the results of running the program are different even though they are running at the same time.

Because multithreading has one feature: randomness.

Cause: the CPU continuously switches to process various threads in an instant.

It can be understood that multiple threads are scrambling for CPU resources.

1.2 comparison between threads and processes

A thread has many characteristics of a traditional process, so it is also called a lightweight process or process element. a traditional process is called a heavy process, which is equivalent to a task with only one thread. In the operating system where threads are introduced, a process usually has several threads and requires at least one thread.

Differences between processes and threads:

1. The process has an independent process space, and the data storage space (heap space and stack space) in the process is independent.

2. The thread heap space is shared, the stack space is independent, and the resources consumed by the thread are smaller than those consumed by the process, which can affect each other.

For details about threads and processes, see "detailed analysis of threads and processes".

2. Create thread 2.1 create thread first method (inheritance ):

1. Create a new class that inherits the thread

2. re-write run Method

3. Create a thread object

4. Start the thread (thread object. Start ())

The Code is as follows:

class MyThread extends Thread{public void run() {for (int i = 0; i < 100; i++) {System.out.println("MyThread---->"+ i);}}}class ThreadDemo1 {public static void main(String[] args) {for (int i = 0; i < 100; i++) {System.out.println("main------>" +i);if(i == 10){new MyThread().start();}}    }}

2.2 Method 2 for thread creation (Implementation ):

Implement the runnable interface
1. Subclass overwrites the run method in the interface.
2. Create a thread through the Thread class and pass the subclass object that implements the runnable interface to the constructor of the thread class as a parameter.
3. The thread Class Object calls the start method to enable the thread.
The Code is as follows:

Class mythread2 implements runnable {public void run () {// thread body for (INT I = 0; I <100; I ++) {system. out. println ("mythread2 ----->" + I) ;}} public class threaddemo2 {public static void main (string [] ARGs) {for (INT I = 0; I <100; I ++) {system. out. println ("Main -->" + I); if (I = 10) {New thread (New mythread2 ()). start ();}}}}

Now we use a classic case to illustrate the differences between the two methods:

Ticket sales example. This example is basically available in every Java getting started book!

Requirement: If you have 50 tickets, you need to sell them in three ticket sales windows. You can use two ways to enable the thread to buy tickets. What are the differences between the two methods?

1. inherit the thread method

Class ticket1 extends thread {int num = 20; Public ticket1 (string name) {super (name);} public void run () {for (INT I = 0; I <100; I ++) {If (Num> 0) {system. out. println (getname () + "" + num -- + "") ;}}} public class ticketdemo {public static void main (string [] ARGs) {// buy new ticket1 ("conductor-1") in three windows "). start (); New ticket1 ("conductor-2 "). start (); New ticket1 ("conductor-3 "). start ();}}

Part of the output result:

 Ticket conductor-1 sold 50th sheets

Ticket conductor-3 sold 50th sheets

Ticket conductor-2 sold 50th sheets

Ticket conductor-3 sold 49th sheets

Ticket conductor-1 sold 49th sheets

Ticket conductor-3 sold 48th sheets


Ticket conductor-3 sold 47th sheets


2. Implement the runnable Mode

Class ticket2 extends object implements runnable {int num = 20; Public void run () {for (INT I = 0; I <50; I ++) {If (Num> 0) {system. out. println (thread. currentthread (). getname () + "selling" + num -- + "Zhang ");
}}} Public class ticketdemo2 {public static void main (string [] ARGs) {runnable target = new ticket2 (); New thread (target, "conductor-1 "). start (); New thread (target, "conductor-2 "). start (); New thread (target, "conductor-3 "). start ();}}

Part of the output result:

Ticket conductor-1 sold 50th sheets

Ticket conductor-3 sold 48th sheets

Ticket conductor-2 sold 49th sheets

Ticket conductor-3 sold 46th sheets

Ticket conductor-2 sold 45th sheets

Ticket conductor-2 sold 43rd sheets


Currentthread (): returns a reference to the currently executed thread object.

Getname (): Get the thread name.

Setname () sets the thread name.

Compare the output results of the two methods, we will find that

The output results of the inherited Thread class are printed with a total of 150 entries, indicating that one ticket was sold three times, which is obviously incorrect.

The runnable interface is not implemented.

Explanation:

Because a thread can only be started once. When a thread is used to implement a thread, the thread and the task to be executed by the thread are bundled together. In this way, only one thread can be started for a task, and the tasks executed by different threads are different. Therefore, it is not necessary to allow two threads to share resources of each other's tasks.

A task can start multiple threads and implement the threads in runnable mode. In fact, a thread is opened up to pass the task in, and thus the thread is executed. Multiple thread objects can be instantiated, and the same task can be passed in, that is, a task can start multiple threads to execute it. These threads execute the same task, so their resources are shared.

Two different thread implementation methods determine whether they can share resources.

Inherit thread

Same resources are not shared and the program will not be extended in the future due to Java's single inheritance.

Runnable implementation: (recommended)

Multiple threads share one target resource, which is suitable for processing the same resource in multiple threads.

This class can inherit other classes or implement other interfaces.


3. Thread Lifecycle


3.1 Creation and readiness of thread Lifecycle

New: when a program uses new to create a thread, the thread is in the new State. In this case, like other Java objects, the Java Virtual Machine only allocates memory for the thread and initializes the member variable value. [Thread r = new thread ()]

Ready: When the thread object calls the START () method, the thread is in the ready state, and the thread is included in the thread queue. At this time, the thread in this state does not start to run, and it only indicates that it can run. When the thread runs depends on the scheduling of the JVM thread scheduler. [R. Start ()]

3.2 The running and blocking status of the thread's life cycle

Run: If a ready thread obtains the CPU, it starts to execute the run () thread execution body, which is in the execution state.

Blocking: the thread needs to be interrupted during running, so that other threads can get execution opportunities. This status will enter the blocking status.

Note: The blocking status cannot be changed directly to the running status. The blocking status can only be changed to the ready status again.

3.3 thread lifecycle death

Run () execution is complete, and the thread ends normally; the thread throws an uncaptured exception or error;

Stop () of the calling thread (). (Deadlock is easily caused and not recommended)

Note:

After the main thread ends, other threads are not affected and will not end;

Once the child thread starts, it has the same status as the main thread and is not affected by the main thread.

Test whether the thread is alive. The isalive () method of the thread object is available. When the thread is in the ready state, running, blocking status returns true. If the thread is in the new and dead state, false is returned.

The dead thread cannot wake up the thread by using the START () method. Otherwise, the illegalthreadstateexception is thrown;

Lou pig is not a big bull, but I think it is still a good summary and it is suitable for beginners. If you find something wrong, please kindly advise!

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.