Java multithreaded Usage Programming summary _java

Source: Internet
Author: User
Tags thread class throwable ticket

A, process and thread

1. What is the process?

Narrowly defined: Processes are instances of running programs (an instance of the a computer program, is being executed).

Generalized definition: A process is a program with a certain number of independent functions about a data collection of a running activity. It is the basic unit of operating system dynamic execution, in the traditional operating system, the process is both the basic allocation unit and the basic execution unit.

2, what is the thread?

threads, sometimes referred to as lightweight processes (lightweight PROCESS,LWP), are the smallest units of program execution flow. A standard thread consists of a thread ID, a current instruction pointer (PC), a register collection, and a stack. In addition, a thread is an entity in a process, the basic unit of a system that is independently dispatched and dispatched, and the thread itself does not own system resources and has a little bit of the resources necessary to run, but it can share all the resources owned by the process with other threads of the same process.

3. What is the difference between process and thread?

The main difference between processes and threads is that they are different ways of managing operating system resources.

Processes have separate address spaces, and when a process crashes, it does not affect other processes in protected mode, and threads are just different execution paths in a process.

Thread has its own stack and local variables, but there is no separate address space between the threads, one thread dead is equal to the entire process dead, so the process of multiple processes than multithreaded program is robust, but in the process of switching, the resource consumption is greater, the efficiency is some worse. However, for concurrent operations that require simultaneous and share certain variables, only threads can be used, and processes cannot be used.

In short, the difference between a thread and a process is:

(1) A program has at least one process, and a process has at least one thread;
(2) The thread partitioning scale is smaller than the process, which makes the multithreading procedure more concurrent.
(3) The process has a separate memory unit in the process of execution, while multiple threads share the memory, which greatly improves the running efficiency of the program.
(4) The thread differs from the process in the execution process. Each independent thread has a program to run the entry, sequential execution sequence, and exit of the program. However, threads cannot be executed independently, and must be dependent on the application, which provides multiple thread execution control by the application.
(5) from a logical point of view, the meaning of multithreading is that in one application, there are multiple execution parts that can be executed concurrently. However, the operating system does not consider multiple threads as multiple independent applications to implement process scheduling and management and resource allocation.

This is the important difference between process and thread.

Two, the life cycle of the thread and five kinds of basic state

There are five basic states of Java threads:

(1) New State (new): When the thread object is created, it enters a new state, such as: thread t = new mythread ();

(2) Ready State (Runnable): When the calling thread object's start () method (T.start ();), the thread enters the ready state. A thread in the ready state simply indicates that the thread is ready to wait for CPU scheduling to execute, not that the T.start () is executed immediately;

(3) running state (Running): When the CPU begins to dispatch a thread that is in a ready state, the thread can actually execute, that is, into the running state. Note: The ready state is the only entry into the running state, that is, the thread must first be in the ready state in order to enter the running state.

(4) Blocking state (Blocked): In the running state of the thread for some reason, temporarily give up the right to use the CPU, stop execution, at this time into a blocking state, until it enters the ready state, only the opportunity to be called by the CPU to enter the running state. Depending on the cause of the blockage, the blocking state can be divided into three different kinds:

① wait for blocking: the thread in the running state executes the wait () method, which causes the thread to enter the waiting block state;

② synchronous blocking: The thread fails to get the Synchronized Sync lock (because the lock is occupied by another thread) and it enters the synchronized blocking state;

③ Other blocking: The thread enters the blocking state by calling the thread's sleep () or join () or by making an I/O request. When the sleep () state times out, join () waits for the thread to terminate or timeout, or the I/O process completes, the thread is back in ready state.

(5) The State of Death (Dead): The thread has finished or exited the run () method because of an exception, which ends the lifecycle.

Three, Java Multi-threading implementation

In Java, if you want to implement multithreaded programs, you must rely on a thread's principal class (like the concept of the main class to represent the main class of a thread), but the thread's body class needs to have some special requirements when it's defined. This class can inherit the thread class or implement the Runnable interface to complete the definition.

1, inheritance thread class to achieve multithreading

Java.lang.Thread is a class that is responsible for threading operations, and any class that inherits the thread class can become the main class of a thread. Since it is the main class, there must be a way to use it, and the thread-initiated main method needs to overwrite the run () method in the thread class.

Define the body class for a thread:

Class Mythread extends Thread {//thread's principal class
 private String title;

 Public Mythread (String title) {
 this.title = title;
 }

 @Override public
 Void Run () {//thread's Main method for
 (int x = 0; x < x. x + +) {
  System.out.println (this.title +) run, x = "+ X";}}}

Now that there is a thread class, and there is a corresponding method of operation, then the object should be generated and call the methods inside, and then write the following program:

public class Testdemo {public
 static void Main (string[] args) {
 mythread mt1 = new Mythread ("Thread A");
 Mythread mt2 = new Mythread ("Thread B");
 Mythread mt3 = new Mythread ("Thread C");
 Mt1.run ();
 Mt2.run ();
 Mt3.run ();
 }

Run Result:

Thread A runs, x = 0
Thread A runs, x = 1
Thread A runs, x = 2
Thread A runs, x = 3
Thread A runs, x = 4
Thread A runs, x = 5
Thread A runs, x = 6
Thread A runs, x = 7
Thread A runs, x = 8
Thread A runs, x = 9
Thread B runs, x = 0
Thread B runs, x = 1
Thread B runs, x = 2
Thread B runs, x = 3
Thread B runs, x = 4
Thread B runs, x = 5
Thread B runs, x = 6
Thread B runs, x = 7
Thread B runs, x = 8
Thread B runs, x = 9
Thread C Run, x = 0
Thread C Run, x = 1
Thread C Run, x = 2
Thread C Run, x = 3
Thread C Run, x = 4
Thread C Run, x = 5
Thread C Run, x = 6
Thread C Run, x = 7
Thread C Run, x = 8
Thread C Run, x = 9

We found that the above operation does not really start multithreading, because the execution of multiple threads between each other must be run alternately, and this time is sequential execution, the code of each object is executed before continuing down.

If you want to actually start multiple threads in a program, you must rely on one method of the thread class: public void Start (), which means that you actually start multiple threads, calling this method indirectly calling the run () method:

public class Testdemo {public
 static void Main (string[] args) {
 mythread mt1 = new Mythread ("Thread A");
 Mythread mt2 = new Mythread ("Thread B");
 Mythread mt3 = new Mythread ("Thread C");
 Mt1.start ();
 Mt2.start ();
 Mt3.start ();
 }


Run Result:

Thread C Run, x = 0
Thread A runs, x = 0
Thread B runs, x = 0
Thread A runs, x = 1
Thread C Run, x = 1
Thread A runs, x = 2
Thread B runs, x = 1
Thread A runs, x = 3
Thread A runs, x = 4
Thread A runs, x = 5
Thread C Run, x = 2
Thread C Run, x = 3
Thread C Run, x = 4
Thread C Run, x = 5
Thread C Run, x = 6
Thread C Run, x = 7
Thread C Run, x = 8
Thread C Run, x = 9
Thread A runs, x = 6
Thread A runs, x = 7
Thread A runs, x = 8
Thread A runs, x = 9
Thread B runs, x = 2
Thread B runs, x = 3
Thread B runs, x = 4
Thread B runs, x = 5
Thread B runs, x = 6
Thread B runs, x = 7
Thread B runs, x = 8
Thread B runs, x = 9

At this point you can see that multiple threads are performing alternately between each other, but each execution result is different. You can conclude from the above code that the start thread must depend on the thread class's start () method, and the run () method is invoked by default after the thread starts.

After invoking the start () method, a series of complex things happened:
(1) Start a new execution thread (with a new call stack);
(2) The thread is transferred from the new state to a running state;
(3) When the thread gets an opportunity to execute, its target run () method runs.
Note: There is nothing special about the run () method for Java. Like the main () method, it is just the method name (and signature) that the new thread knows the call. Therefore, it is legitimate to use the Run method on runnable or thread, but it does not start a new thread.

Description: Why must the thread start by calling start () instead of calling run () directly?

What we found was that after we called start (), it actually executed the write-behind run () method, so why not call the run () method directly? To explain this issue, open the source code for the thread class and observe the definition of the start () method:

 Public synchronized void Start () {
 if (threadstatus!= 0)
  throw new Illegalthreadstateexception ();
 Group.add (this);
 Boolean started = false;
 try {
  start0 ();
  started = true;
 } Finally {
  try {
  if (!started) {
   group.threadstartfailed (this);
  }
  catch (Throwable ignore) { c14/>}}}
 private native void Start0 ();

The source code that opens this method can be found first: The method throws a "Illegalthreadstateexception" exception. In general, if a method uses throw to throw an exception object, then the exception should be used Try...catch capture, or the method of the declaration using the throws throw, but this piece is not, why? Because this exception class is a subclass of a Run-time exception (RuntimeException):

Java.lang.Object
|-java.lang.Throwable
|-java.lang.Exception
|-java.lang.RuntimeException
|-java.lang.IllegalArgumentException
|-java.lang.IllegalThreadStateException

This exception is thrown when a thread object is repeatedly started: a thread object can only be started once.

One of the most critical parts of the start () method is the Start0 () method, and the method uses a native keyword definition.

The Native keyword refers to the Java local interface invocation (Java Native Interface), which is a function that uses Java to invoke the native operating system to perform some special operations, and such code development is rarely seen in Java, Because the biggest feature of Java is portability, if a program can only be used on a fixed operating system, then the portability will be completely lost, so, this operation is generally not.

The implementation of multithreading must require the support of the operating system, so the above Start0 () method is actually similar to the abstract method without a method body, and this method body to the JVM to implement, namely: the JVM under Windows may use a method to implement Start0 (), In Linux, the JVM may use the B method to implement Start0 (), but in the call does not care about how to implement the Start0 () method, will only care about the final results of the operation, to the JVM to match the different operating systems.

So in multithreaded operations, using the Start () method to start a multithreaded operation requires operating system function calls.

2, implement runnable interface to achieve multithreading

Using the thread class is really a convenient way to implement multithreading, but the biggest drawback of this approach is the problem of single inheritance. To do this, in Java can also use the Runnable interface to achieve multithreading. This interface is defined as follows:

Public interface Runnable {public
 void run ();
}

Multithreading via Runnable interface:

Class Mythread implements Runnable {//thread's main class
 private String title;

 Public Mythread (String title) {
 this.title = title;
 }

 @Override public
 Void Run () {//thread's Main method for
 (int x = 0; x < x. x + +) {
  System.out.println (this.title +) row, x = "+ x);}}}"

This differs from the way the thread class was inherited before, but one advantage is that it avoids the single inheritance limitation.

But here's the problem. Previously said, if you want to start multithreading, you need to rely on the thread class start () method to complete, before inheriting the thread class can inherit this method directly to use, but now implement the Runable interface, no this method can inherit, how to do?

To solve this problem, you still need to rely on the thread class to complete it. A construction method is defined in the thread class to receive the Runnable interface object:

Public Thread (Runnable target);

Start multithreading with the thread class:

public class Testdemo {public
 static void Main (string[] args) throws Exception {mythread
 mt1 = new Mythread ("Thread A ");
 Mythread mt2 = new Mythread ("Thread B");
 Mythread mt3 = new Mythread ("Thread C");
 New Thread (MT1). Start ();
 New Thread (MT2). Start ();
 New Thread (MT3). Start ();
 }
}

Run Result:

Thread A runs, x = 0
Thread B runs, x = 0
Thread B runs, x = 1
Thread C Run, x = 0
Thread B runs, x = 2
Thread A runs, x = 1
Thread B runs, x = 3
Thread C Run, x = 1
Thread C Run, x = 2
Thread B runs, x = 4
Thread B runs, x = 5
Thread A runs, x = 2
Thread A runs, x = 3
Thread A runs, x = 4
Thread A runs, x = 5
Thread A runs, x = 6
Thread A runs, x = 7
Thread A runs, x = 8
Thread A runs, x = 9
Thread B runs, x = 6
Thread B runs, x = 7
Thread B runs, x = 8
Thread B runs, x = 9
Thread C Run, x = 3
Thread C Run, x = 4
Thread C Run, x = 5
Thread C Run, x = 6
Thread C Run, x = 7
Thread C Run, x = 8
Thread C Run, x = 9

At this time, not only to achieve the start of multithreading, and no single inheritance limitations.

3, the implementation of multithreading of the third method:. Using callable interface to implement multithreading

Multithreading implemented using the Runnable interface avoids single inheritance limitations, but there is a problem that the run () method in the Runnable interface cannot return the results of the operation. To solve this problem, a new interface is provided: The Callable Interface (java.util.concurrent.Callable).

Public interface callable<v>{Public
 V-call () throws Exception;
}

Executing the call () method in the callable interface returns a result, and the type of the return result is determined by the generics on the callable interface.

Implementation of the callable interface to achieve multithreading of the specific operations are:
Create the implementation class for the callable interface and implement the Clall () method, and then use the Futuretask class to wrap the object of the callable implementation class and create the thread with this Futuretask object as target for the thread object.

Define a thread body class:

Import java.util.concurrent.Callable;

Class Mythread implements callable<string>{

 private int ticket = ten;
 @Override public
 String call () throws Exception {for
 (int i = 0; i < i++) {
  if (This.ticket > 0) {
   system.out.println ("Sell the ticket, the remaining votes are" + this.ticket-)
  ;
 }
 Return "The ticket has been sold out";
 }


The thread class does not directly support the callable interface. After JDK1.5, a class is provided:

Java.util.concurrent.futuretask<v>

This class is primarily responsible for callable interface object operations. The definition structure is as follows:

public class Futuretask<v>
Extends Object
Implements Runnablefurture<v>

And runnablefurture This interface has the following definition:

public interface runnablefurture<v>
Extends runnable,future<v>

The following construction methods are defined in the Futuretask class:

Public Futuretask (callable<v> callable)

It is now possible to receive the callable interface object through the Futuretask class, which is intended to obtain the return result of the call () method.

From the above analysis we can find:
The Futuretask class can receive the callable interface object, while the Futuretask class implements the Runnablefurture interface, and the Runnablefurture interface inherits the Runnable interface.

So we can start multithreading in this way:

public class Testdemo {public
 static void Main (string[] args) throws Exception {mythread
 mt1 = new Mythread (); 
   mythread mt2 = new Mythread ();

 futuretask<string> Task1 = new futuretask<string> (MT1);//Get Call () method returns the result
 futuretask<string> Task2 = new futuretask<string> (MT2); the call () method returns the result

 //futuretask is a subclass of the Runnable interface, you can use the construct of the thread class to receive the Task object
 new Thread (Task1). Start ();
 New Thread (Task2). Start ();

 After multithreaded execution, you can use the Get () method in the Futuretask parent interface future to obtain the execution result
 System.out.println ("Return result of thread 1:" +task1.get ());
 SYSTEM.OUT.PRINTLN (return result of thread 2: +task2.get ());
 }


Run Result:

Sell the ticket, the remaining number is 10
Sell the ticket, the remaining number is 10
Sell the ticket, the remaining number is 9
Sell the ticket, the remaining number is 8
Sell the ticket, the remaining number is 7
Sell the ticket, the remaining number is 9
Sell the ticket, the remaining number is 6
Sell the ticket, the remaining number is 8
Sell the ticket, the remaining number is 5
Sell the ticket, the remaining number is 7
Sell the ticket, the remaining number is 4
Sell the ticket, the remaining number is 6
Sell the ticket, the remaining number is 3
Sell the ticket, the remaining number is 5
Sell the ticket, the remaining number is 2
Sell the ticket, the remaining number is 4
Sell the ticket, the remaining number is 1
Sell the ticket, the remaining number is 3
Sell the ticket, the remaining number is 2
Sell the ticket, the remaining number is 1
return result of thread 1: tickets sold OUT
return result of Thread 2: tickets sold OUT

Summary:

This explains three ways to implement multithreading, for thread startup, is the call thread object's start () method, you need to pay special attention to: the same thread object cannot call the start () method two times.

Related Article

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.