2016.3.8 (multi-threaded)

Source: Internet
Author: User
Tags thread class

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

Package com.multithread.learning;/** */class Thread1 extends thread{private String name;    Public Thread1 (String name) {       this.name=name;    } public void Run () {for        (int i = 0; i < 5; i++) {            System.out.println (name + "Run  :  " + i);            try {                sleep (int) math.random () *),            } catch (Interruptedexception e) {                e.printstacktrace ();}        }       }} public class Main {public static void main (string[] args) {Thread1 mth1=new Thread1 ("A"); Thread1 mth2=new Thread1 ("B"); Mth1.start (); Mth2.start ();}}

Output:

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

Run it again:

A run: 0
B Run: 0
B Run: 1
B Run: 2
B Run: 3
B Run: 4
A run: 1
A run: 2
A run: 3
A 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.

Thread1 mth1=new Thread1 ("A"); Thread1 Mth2=mth1;mth1.start (); Mth2.start ();


Output:

Exception in thread "main" java.lang.IllegalThreadStateException
At Java.lang.Thread.start (Unknown Source)
At Com.multithread.learning.Main.main (main.java:31)
A run: 0
A run: 1
A run: 2
A run: 3
A run: 4

Second, realize java.lang.Runnable interface

/** * @functon multithreaded Learning */package com.multithread.runnable;class Thread2 implements Runnable{private String Name;public Thread2 (String name) {this.name=name;} @Overridepublic void Run () {for  (int i = 0; i < 5; i++) {            System.out.println (name + "Run  :  " + i);            try {            thread.sleep (int) math.random () *),            } catch (Interruptedexception e) {                e.printstacktrace ();            }        }}} public class Main {public static void main (string[] args) {new Thread (new Thread2 ("C")). Start (); New Thread (New Thread2 ("D" ). Start ();}}

Output:

C Run: 0
D Run: 0
D Run: 1
C Run: 1
D Run: 2
C Run: 2
D Run: 3
C Run: 3
D Run: 4
C 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.

Package com.multithread.learning;/** * @functon multithreaded learning, inherit thread, resources cannot share */class Thread1 extends thread{private int count=5 ;p rivate String name;    Public Thread1 (String name) {       this.name=name;    } public void Run () {for        (int i = 0; i < 5; i++) {            System.out.println (name + "Run  count=" + count--);            try {                sleep (int) math.random () *),            } catch (Interruptedexception e) {                e.printstacktrace ();}        }       }} public class Main {public static void main (string[] args) {Thread1 mth1=new Thread1 ("A"); Thread1 mth2=new Thread1 ("B"); Mth1.start (); Mth2.start ();}}

Output:

B Running count= 5
A running count= 5
B Running count= 4
B Running count= 3
B Running count= 2
B running count= 1
A running count= 4
A running count= 3
A running count= 2
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.

/** * @functon Multi-threaded learning inherits runnable, resources can share */package Com.multithread.runnable;class Thread2 implements runnable{    private int count=15; @Overridepublic void Run () {for  (int i = 0; i < 5; i++) {  System.out.println (thread.currentthread (). GetName () + "Run  count=" + count--);            try {            thread.sleep (int) math.random () *),            } catch (Interruptedexception e) {                e.printstacktrace ();            }        }}} public class Main {public static void main (string[] args) {Thread2 my = new Thread2 ();        New Thread (My, "C"). Start ();//the same MT, but not in Thread, if you use the same instantiated object MT, the exception           new thread (My, "D") will appear. Start ();        New Thread (My, "E"). Start ();}}


Output:

C Running count= 15
D Run count= 14
E Run count= 13
D Run count= 12
D Run count= 10
D Run count= 9
D Run count= 8
C Running count= 11
E Run count= 12
C Running count= 7
E Run count= 6
C Running 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.

2016.3.8 (multi-threaded)

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.