Java Multithreaded Learning

Source: Internet
Author: User
Tags thread class

Let's start by talking about the differences between processes and threads:

Process: Each process has its own code and data space (process context), and there is a significant overhead of switching between processes, and a process contains 1--n threads.

Threads: The same class of threads share code and data space, each thread has a separate run stack and program counter (PC), and thread switching overhead is small.

  Threads and processes are divided into five phases: Create, ready, run, block, terminate.

Multi-process means that the operating system can run multiple tasks (programs) at the same time.

Multithreading refers to the execution of multiple sequential streams in the same program.

In Java to implement multi-threading, there are two ways, one is to continue the thread class, and the other is to implement the Runable interface.

First, extend the Java.lang.Thread class
 Packagecom.hanqi.test; Public classThread1extendsThread {PrivateString name;  PublicThread1 (String name) { This. Name =name; }     Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run" +i); }        Try{sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }    }     Public Static classMain { Public Static voidMain (string[] args) {Thread1 T1=NewThread1 ("A"); Thread1 T2=NewThread1 ("B");            T1.start ();        T2.start (); }    }}

Output:

B Run 0
B Run 1
B Run 2
B Run 3
B Run 4
A run 0
A Run 1
A Run 2
A Run 3
A run 4

Run once more:

A run 0
B Run 0
A Run 1
B Run 1
A Run 2
B Run 2
A Run 3
B Run 3
A run 4
B Run 4

Description: When the program starts running main, the Java Virtual machine starts a process, and the main thread is created at the main () call. With the Start method of the two objects that call Mitisay, another two threads are also started, so that the entire application runs under multiple threads. Note: Instead of executing multithreaded code immediately after the call to the start () method, the thread becomes operational (Runnable) and when it is run is determined by the operating system. The results from the running of the program can be found that multi-threaded programs are executed in a disorderly order. Therefore, only code that executes in a disorderly order is necessary to be designed as multithreaded. The purpose of the Thread.Sleep () method call is to not allow the current thread to occupy the CPU resources acquired by the process alone to allow a certain amount of time for other threads to execute. Virtually all multithreaded code execution sequences are indeterminate, and the results of each execution are random.

However, the Start method repeats the call and the java.lang.IllegalThreadStateException exception occurs.

 Public Static class Main {        publicstaticvoid  main (string[] args) {            Thread1 mTh1= New Thread1 ("A");              Thread1 mTh2=mTh1;              Mth1.start ();              Mth2.start ();        }}

Output:

Exception in thread "main"

A run 0
A Run 1
A Run 2
A Run 3
A run 4
Java.lang.IllegalThreadStateException
At Java.lang.Thread.start (thread.java:705)
At Com.hanqi.test.thread1$main.main (thread1.java:26)

Second, realize java.lang.Runnable interface
 Packagecom.hanqi.runnable;classThread2ImplementsRunnable {PrivateString name;  PublicThread2 (String name) { This. Name =name; } @Override Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run:" +i); Try{Thread.Sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }} Public classMain { Public Static voidMain (string[] args) {NewThread (NewThread2 ("C") . Start (); NewThread (NewThread2 ("D") . Start (); }}

Output:

C Run: 0
D Run: 0
C Run: 1
D Run: 1
C Run: 2
D Run: 2
C Run: 3
D Run: 3
C Run: 4
D Run: 4

Description: By implementing the Runnable interface, the Thread2 class has the characteristics of multithreaded classes. The run () method is a convention for multi-threaded procedures. All multithreaded code is inside the Run method. The thread class is actually a class that implements the Runnable interface. At the start of multithreading, you need to construct the object through the thread class's construction method, thread (Runnable target), and then call the start () method of the thread object to run the multithreaded code. In fact, all multithreaded code is run by running the thread's start () method. Therefore, whether you are extending the thread class or implementing a runnable interface to implement multi-threading and ultimately control threading through the API of the thread's object, the API familiar with the thread class is the basis for multithreaded programming.
Three, the difference between thread and runnable

If a class inherits the thread, it is not suitable for resource sharing. However, if the Runable interface is implemented, it is easy to realize the resource sharing.

 Packagecom.multithread.learning; /*** @functon Multi-threaded learning, inherit thread, resources cannot be shared *@authorLin Bingwen * @time 2015.3.9*/  classThread1extendsthread{Private intCount=5; PrivateString name;  PublicThread1 (String name) { This. name=name; }       Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (name+ "Run count=" + count--); Try{sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }          }               }  }     Public classMain { Public Static voidMain (string[] args) {Thread1 mTh1=NewThread1 ("A"); Thread1 MTH2=NewThread1 ("B");          Mth1.start ();        Mth2.start (); }    }  

Output:

A running count= 5
B Running count= 5
B Running count= 4
A running count= 4
B Running count= 3
A running count= 3
B Running count= 2
A running count= 2
B running count= 1
A running count= 1

As can be seen from the above, the count is different between different threads, which will have a lot of problems for the ticketing system, of course, this can be done with synchronization. Here, let's take a look at the runnable.

 Packagecom.multithread.runnable; classThread2Implementsrunnable{Private intCount=15; @Override Public voidrun () { for(inti = 0; I < 5; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "Run count=" + count--); Try{Thread.Sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }              }                }        }   Public classMain { Public Static voidMain (string[] args) {Thread2 my=NewThread2 (); NewThread (My, "C"). Start ();//The same MT, but not in thread, if you use the same instantiated object MT, an exception will occur            NewThread (My, "D"). Start (); NewThread (My, "E"). Start (); }    }  

Output:

C Running count= 15
E Run count= 13
D Run count= 14
D Run count= 12
C Running count= 11
E Run count= 11
D Run count= 10
C Running count= 9
D Run count= 8
E Run count= 7
C Running count= 6
D Run count= 5
E Run count= 4
C Running count= 3
E Run count= 2

It is important to note that each thread is instantiated with the same object, and if it is not the same, the effect is the same as above!

Summarize:

The benefits of implementing the Runnable interface are more than inheriting the thread class:

1): Suitable for multiple threads of the same program code to process the same resource

2): Can avoid the restriction of single inheritance in Java

3): Increase the robustness of the program, the code can be shared by multiple threads, code and data Independent

Remind everyone: The Main method is actually a thread. In Java so the threads are all started at the same time, as to when, which first executes, fully see who first get the CPU resources.

In Java, at least 2 threads are started each time a program runs. One is the main thread and one is the garbage collection thread. Because every time a class is executed with a Java command, a JVM is actually started, and each JVM internship starts a process in the operating system.

Iv. Thread State transitions

1. New state: A new Thread object was created. 2. Ready state (Runnable): After the thread object is created, other threads call the object's start () method. The state of the thread is located in a pool of running threads that becomes operational and waits for the CPU to be used. 3, running State (Running): The ready state of the thread gets the CPU, executes the program code. 4, blocking State (Blocked): Blocking state is the thread for some reason to abandon the use of the CPU, temporarily stop running. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking: (i), waiting for blocking: The running thread executes the wait () method, and the JVM puts the thread into the waiting pool. (ii), synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts the thread into the lock pool if the synchronization lock is occupied by another thread. (iii), other blocking: The running thread executes the sleep () or join () method, or when an I/O request is made, the JVM will place the thread in a blocked state. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state. 5. Dead State (Dead): The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle. Five, thread scheduling

Scheduling of Threads

1, adjust the thread priority: Java threads have priority, high priority threads will get more running opportunities. The priority of a  java thread is expressed in integers, and the value range is the following three static constants for the 1~10,thread class: Static int max_priority       The     thread can have the highest priority, with a value of 10. The static int min_priority          thread can have the lowest priority, with a value of 1. The static int norm_priority          The default priority assigned to the thread, with a value of 5. The SetPriority () and GetPriority () methods of the  thread class are used to set and get the priority of the thread, respectively.   Each thread has a default priority. The default priority for the primary thread is thread.norm_priority. The priority of a thread has an inheritance relationship, such as the B thread created in a thread, then B will have the same priority as a. The JVM provides 10 thread priorities, but does not map well with common operating systems. If you want the program to be portable to each operating system, you should only use the thread class with the following three static constants as priority, which ensures that the same precedence is used for the same scheduling. &NBSP;2, Thread sleep: thread.sleep (Long Millis) method, which causes the thread to go to the blocking state. The Millis parameter sets the time to sleep, in milliseconds. When sleep is over, it becomes ready (Runnable) state. Sleep () platform portability is good.  3, thread wait: The Wait () method in the object class causes the current thread to wait until the other thread calls the Notify () method of this object or the Notifyall () Wake method. This two wake-up method is also a method in the object class, and behaves equivalent to calling wait (0).  4, thread Concession: the Thread.yield () method pauses the currently executing thread object, giving the execution opportunity to the same or higher priority thread.  5, thread join: Join () method, wait for other threads to terminate. Calling the Join () method of another thread in the current thread, the current thread goes into a blocking state until anotherThe process runs to the end, and the current thread is then turned into a ready state by blocking.  6, Thread Wake: The Notify () method in the object class, which wakes up a single thread waiting on this objects monitor. If all threads are waiting on this object, then one of the threads is chosen to wake up. The choice is arbitrary and occurs when a decision is made on the implementation. The thread waits on the object's monitor by calling one of the wait methods. Until the current thread discards the lock on this object, it can continue to execute the awakened thread. The awakened thread competes with all other threads that are actively synchronizing on the object, for example, the thread that wakes up does not have a reliable privilege or disadvantage as the next thread that locks the object. A similar approach also has a notifyall () that wakes up all the threads waiting on this object monitor.   NOTE: Thread suspend () and resume () Two methods have been abolished in JDK1.5 and are no longer introduced. Because there is a deadlock tendency.

Java Multithreaded Learning

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.