Javase Getting Started learning 50: Multithreaded Programming (i)

Source: Internet
Author: User

a process and a thread (1) Basic concepts of processes and threads

Process: The execution of a program (task), the holding of resources (shared memory, shared files), and threads.

Thread: is the sequential control flow within a program.

There are many examples of processes in our lives, and a process is the equivalent of a program that you start on your computer. For example, we open the most used chat tool

QQ, you can also open the Java development tool eclipse and so on. These are counted as a process on the window operating system.

For a window operating system on a thread, or take QQ process and eclipse process to illustrate, QQ process text chat and send and receive files is

Two of these threads, the source code file editing, source compilation, and syntax checking in the eclipse process are the three threads.

through the above knowledge can be drawn:                     

1) A process can have multiple threads;

2) The thread is the smallest execution unit in the system;

3) There are multiple threads in the same process;

4) Threads share the resources of the process.

(2) The difference between threads and processes

Each process has its own code and data space (in context), and there is a significant overhead involved in switching between processes. Multi-process refers to the operating system

Run multiple tasks (programs) at the same time.

Threads can be thought of as lightweight processes, sharing code and data spaces with a class of threads, each with a separate run stack and program counter (PC), line

The cost of the process switch is small. Multithreading refers to the simultaneous execution of multiple sequential streams in the same program.

(3) Thread interaction

Communication between threads consists of mutual exclusion and synchronization.

Mutual exclusion : it usually manifests itself in multiple threads competing for the same resource, for example, there is only one pen, and several people have to sign in, but the resource (pen) is the only,

There is a competitive relationship between the threads (people), and only one thread (person) can hold the capital (pen) at the same time.

Synchronization : Synchronization is a coordinated pace, in a predetermined sequence of operations, such as process, thread synchronization, can be understood as a process or thread A and b a

A to a certain extent, a result of B, so stop down, motioned B to run, B according to the words to execute, and then the result to A;a continue to operate.

two Java multithreading

Java multithreading is implemented through the Java.lang.Thread class. When the VM starts, it is defined by the main method (public static void Main () {})

The thread. You can create a new thread by creating an instance of the thread class. Each thread is a method that corresponds to an object of a particular thread class

Run () to complete its the method run () is called the thread body. Start a thread by calling the start () method of the thread class.

(1) thread class

The thread class defined in the API:

A thread is a thread of execution in a program. A Java Virtual machine allows an application to run multiple execution threads concurrently. Each thread has a priority, high-

The execution of the first-level thread takes precedence over the low-priority thread. Each thread can or cannot be marked as a daemon. When code that runs in a thread is created

When a new thread object is created, the initial priority of the new threads is set to the priority of the creation thread, and if and only if the creation thread is the daemon thread,

The new thread is the daemon.

When a Java virtual machine is started, it usually has a single non-daemon thread (which typically invokes the main () method of a specified class. Java Virtual Opportunity continues

Executes the thread until any of the following conditions occur:

1) The exit () method of the runtime class is called, and the security Manager allows the exit operation to occur.

2) All threads that are not daemon threads have stopped running, either by returning from a call to the run () method or by throwing a propagate to run ()

Exception that is outside the method.

There are two ways to create a new thread of execution. One way is to declare a class as a subclass of the thread class. The subclass should override the run () method of the thread class. Pick up

You can assign and start an instance of the subclass. For example, a thread that calculates a prime number larger than a specified value can be written as:

Class Primethread extends Thread {       long minprime;       Primethread (Long minprime) {           this.minprime = minprime;       }       public void Run () {           //compute primes larger than minprime            ...       }}

The following code then creates and starts a thread:

Primethread p = new Primethread (143); P.start ();

Another way to create a thread is to declare a class for the real runnable interface. The class then implements the run () method. You can then assign instances of this class to the

built The thread class is passed and started as a parameter. The same example of using this style is as follows:

Class Primerun implements Runnable {         long minprime;         Primerun (Long minprime) {             this.minprime = minprime;         }          public void Run () {             //compute primes larger than minprime              ...         }}

The following code then creates and starts a thread:

Primerun p = new Primerun (143); new Thread (P). Start ();

Each thread has an identity name, and multiple threads can have the same name. If the thread is created without specifying an identity name, a new name is generated for it.

a field in the thread class that defines the priority of the threads:


constructed methods defined in the thread class:


methods defined in the thread class:






(2) runnable interface

The runnable interface described in the API:

The runnable interface should be implemented by classes that intend to execute their instances through a thread. The class must define a parameterless method called run ().

The purpose of designing the Runnable interface is to provide a common protocol for objects that want to execute code at activity time. For example, the thread class implements the Runnable connection

Mouth. Activation means that a thread has started and has not stopped.

In addition, the Runnable interface provides an activation method for classes that are not thread subclasses. By instantiating an instance of a thread class and using itself as an operational

Row target, you can run a class that implements the Runnable interface without creating a subclass of the thread class. In most cases, if you only want to override the run () method,

Instead of rewriting other thread class methods, you should use the Runnable interface. This is important because unless the programmer intends to modify or enhance the basic line of the class

, you should not create a subclass for the class.

Only one method is defined in the Runnable interface:


(3) thread creation and startup

There are two ways to create a new thread in Java.

The first: Define the threading class to implement the Runnable interface

The thread mythread=new thread (target)//target is the Runnable interface type.

There is only one method in the Runnable interface:

public void run ();//defines the thread-running body.

You can use the Runnable interface to provide shared data for multiple threads.

The static method of thread can be used in the run () method of the class that implements the Runnable interface:

public static thread Correntthread () gets a reference to the current thread

The second type: Define thread class inheritance the thread class

Define a subclass of the thread class and override its run () method such as:

Class MyThread extends thread{

public void Run () {...}

}

The object of the class is then generated:

MyThread MyThread = new MyThread (...)

Instance:

Testthread1.java Source code:

The sequence of method calls executes, that is, the RUNNABLE1 thread is executed first, and then the main thread is executed.

public class TestThread1 {public static void main (String args[]) {<span style= "color: #ff6600;" >runner1 r = new Runner1 (); R.run (); </span>for (int i=0; i<10; i++) {System.out.println ("Main thread:------" + i);}}} Class Runner1 implements Runnable {public void run () {for (int i=0; i<10; i++) {System.out.println ("Runner1 thread:" + i);}}}
Operation Result:


The thread starts the alternating execution, the most important of which is the start () method of the thread class, that is, the RUNNABLE1 thread and the main path are executed alternately.

public class TestThread1 {public static void main (String args[]) {<span style= "color: #ff6600;" >runner1 r = new Runner1 (); Thread t = new Thread (r); T.start (); </span>for (int i=0; i<10; i++) {System.out.println ("Main thread:------" + i);}}} Class Runner1 implements Runnable {public void run () {for (int i=0; i<10; i++) {System.out.println ("Runner1 thread:" + i);}}}

Operation Result:


Use the modified code that inherits the thread class:

public class TestThread1 {public static void main (String args[]) {<span style= "color: #ff6600;" >runner1 r = new Runner1 (); R.start (); </span>for (int i=0; i<10; i++) {System.out.println ("Main thread:------" + i);}}} <span style= "color: #ff6600;" >class Runner1 extends thread</span> {public void run () {for (int i=0; i<10; i++) {System.out.println ("Runner1 Thread: "+ i);}}}

Operation Result:


It is recommended to use thread classes that implement the Runnable interface for multi-threaded creation and startup, which is more flexible.

about the differences between two methods of creating threads

First: The creation thread only inherits the thread class and implements the Runnable interface in two ways (thread also implements the Runnable interface);

Second: If you create a thread with the inherited thread class, an instance of this class can rewrite the dozens of methods of the thread class, and note that it is good for dozens of parties

Law
Third: If you create a thread in a way that implements the Runnable interface, only one run () method is available for rewriting (note that there is only one);

The thread created by implementing the Runnable interface is ultimately going to be executed by passing the instance of itself as a parameter to the thread class, when you want to

The class that inherits the thread class creates the thread, and just wants the instance of the class to call the run () method to perform the task, when the Runnable interface is equivalent to

Your target class provides an activation method that is designed to provide a common protocol for objects that want to execute code at the time of activation,

Live means that a thread has started and has not stopped.

There is no difference between the two methods of creating threads, one is implementing the Runnable interface, and the other is inheriting the thread class. While using the implementation

Runnable interface This method: 1. You can avoid the limitations of Java's single-inheritance features; 2. Code for multiple identical programs to handle the same

The source of the case, the thread with the program code and data effectively separated, better reflect the object-oriented design ideas. The implementation is used in most of the development

Runnable interface This method creates threads.



Javase Getting Started learning 50: Multithreaded Programming (i)

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.