Java Learning Notes-11th chapter multithreading mechanism

Source: Internet
Author: User

The 11th Chapter Java multithreading mechanism

  1. Understanding processes and Threads in Java

    1.1 Process: The structure of a general program can be broadly divided into a single entry, an exit, and a sequential sequence of statements executed. When the program runs, the system starts from the program entrance, completes the instruction according to the order of execution of the statement (including order, branch, and Loop), then exits from the exit and ends the program. Such a structure is called a process. It can be said that a process is the process of a dynamic execution of a program. A process includes both the Code of the program and the resources of the system, such as CPU, memory space, and so on. The system resources occupied by different processes are independent.

    1.2 Threads: A thread is a smaller execution unit than a process. A process can produce multiple threads in order to complete multiple operations at the same time during execution. The thread has no entry, no exit, no Autorun, must exist in a process, and execution is triggered by the process. On the use of system resources, all threads that belong to the same process share the process's system resources.

  2. The life cycle of a thread

    Each Java program has a main thread. For an application, the main thread is the thread that the main () method executes. To implement multi-threading, a new thread object must be created in the main thread. The newly created thread usually needs to experience five states of creation, readiness, operation, blocking, and death in a full life cycle. As shown in the following:


    650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/6C/76/wKioL1VJ43fwscrLAACYy0YJZYs683.jpg "title=" Untitled. png "alt=" wkiol1vj43fwscrlaacyy0yjzys683.jpg "/>

    2.1 New Status:

    When an object of the thread class or its subclasses is declared and created, the newborn thread object is in the new state. For example, the following statement can create a new thread:

    Thread myThread = new Thread ();

    2.2 Ready Status:

    A thread object calls the start () method to make it in a ready state. A thread in the ready state has all the resources required to run the thread except CPU resources. That is, the ready state threads are queued for CPU resources, and this is scheduled by the system.

    2.3 Operating Status:

    A thread that is in a ready state is running when it obtains CPU resources. Each thread class and its subclasses have a run () method that, when the thread is running, automatically calls its own run () method and starts executing the contents of the run () method.

    2.4 Blocking Status:

    A running thread enters a blocking state if it is unable to continue running for any reason. The difference between a blocking state and a ready state is that the readiness state is simply because a lack of CPU resources cannot be performed, and that the blocking state can cause threads to fail to execute for various reasons, not just CPU resources. After the cause of the blocking state is lifted, the thread is again in a ready state, waiting to allocate CPU resources.

    2.5 Death Status:

    When the thread finishes executing the contents of the run () method or is forced to terminate, it is in a dead state. At this point, the life cycle of the thread ends.

  3. Learn how to create threads and start threads

3.1 Creating Threads

There are two ways to create threads in Java: One is to inherit the Java.lang.Thread class, and the other is to implement the Runnable interface.

A. Creating a thread class by inheriting the thread class

Thread classes are defined in Java, and users can create thread classes by inheriting the thread class and overwriting their run () method. The syntax format is as follows:

class <ClassName> extends thread{

public void Run () {

...//Thread execution code

}

}

B. Creating a threading class by implementing the Runnable interface

Class <ClassName> implements runnable{

public void Run () {

...//Thread execution code

}

}

3.2 Thread Start-up

After the thread creation is complete, the thread is run through the thread's startup. The thread class defines the start () method used to complete the startup of the thread.

A. Inherit the start of thread class threads: Call the start () method when you have finished creating the thread object. For example:

Class MyThread extends thread{//inherit the thread class to create a threading class MyThread

public void Run () {//override the Run () method of the Thread class

for (int i = 0; i<10; i++) {

System.out.print (i+ ",")

}

}

}

public class threadexample{

public static void Main (string[] args) {

MyThread MyThread = new MyThread (); To create an instance of the thread class Mythread

Mythread.start (); Start thread

}

}

B. Implement the start of the Runnable interface thread: Create the object based on this class, create the thread class object as a parameter of the thread class constructor method, and finally start the threading by calling the start () method from the thread class object.

Class MyThread implements runnable{//implement Runnable interface Create thread class MyThread

public void Run () {//Implement the Run () method of the Runnable interface

for (int i = 0; i<10; i++) {

System.out.print (i+ ",")

}

}

}

public class threadexample{

public static void Main (string[] args) {

MyThread MyThread = new MyThread (); To create an instance of the thread class Mythread

Thread t = new thread (myThread); To create an instance of the thread class

T.start (); Start thread

}

}


4. Priority of Threads

Multiple threads tend to wait for execution in the ready queue at the same time. The higher the priority, the more it executes, the lower the priority, the later the execution, and the first-in-first-out principle of the queue. The thread class has three static variables that are related to threading precedence, namely:

min_priority: The minimum priority (1) that a thread can have.

max_priority: The maximum priority (10) that a thread can have.

norm_priority: The normal priority of the thread, the default value is 5.

When a thread is created, the priority defaults to the integer 5 identified by the norm_priority. You can set the priority of a thread through the SetPriority () method, or you can get the thread's priority through the GetPriority () method.

The thread scheduling policy of Java is a preemptive scheduling based on priority. High-priority threads preempt the control of the lower-priority thread. But this scheduling strategy is not always effective.

5. Sleep on a thread

For a running thread, you can call the sleep () method to let it discard the CPU resources for hibernation, and this thread becomes blocked. The Sleep () method contains a long parameter that specifies the time, in milliseconds, that the thread sleeps. The sleep () method throws a non-runtime exception interruptedexception, and the program needs to handle the exception.

class MyThread extends thread{

public void Run () {

for (int i = 0; i<10; i++) {

System.out.print (i+ ",");

try{

Sleep (1000); Sleeps 1 seconds, i.e. prints a number every 1 seconds

}catch (Interruptedexception e) {

System.out.print ("Error:" +e);

}

}

}

}

public class threadexample{

public static void Main (string[] args) {

MyThread MyThread = new MyThread ();

Mythread.start ();

}

}

6. Threading Concessions

For a running thread, you can call the yield () method to queue it again in the ready queue and give the CPU resources to the thread that is behind the queue. The thread now transitions to ready state. In addition, the yield () method only withdraws to a high-priority or same-priority thread, and if the ready queue is followed by a low-priority thread, the thread continues to execute. The yield () method has no arguments or throws an exception.

class MyThread extends thread{

public void Run () {

for (int i=0; i<10; i++) {

System.out.print (i);

Yield ();

}

}

}

public class threadexample{

public static void Main (string[] args) {

MyThread myThread1 = new MyThread ();

MyThread myThread2 = new MyThread ();

Mythread1.start ();

Mythread2.start ();

}

}

7. Thread Waits

For a thread that is executing, you can call the join () method to wait for it to end before executing another thread. The join () method has several overloaded forms. where the join () method without parameters represents the end of the wait thread execution. The join () method throws an exception interruptedexception, and the program needs to handle the exception.

class MyThread extends thread{

public void Run () {

for (int i=0; i<10; i++) {

System.out.print (i);

}

}

}

public class threadexample{

public static void Main (string[] args) throws interruptedexceptio{

MyThread myThread1 = new MyThread ();

MyThread myThread2 = new MyThread ();

Mythread1.start ();

Mythread1.join (); Wait for the myThread1 execution to finish.

Mythread2.start ();

}

}

8. Multithreading synchronization mechanism-use of synchronous methods (synchronized)

When you run multiple threads in a program, the following problems may occur: when two or more threads access a variable at the same time, and a thread needs to modify the variable, the program may have unexpected results. To solve such problems, you need to use the Synchronized keyword to lock down the shared resources to achieve thread synchronization. The Synchronized keyword can be used as a modifier for a method or to decorate a block of code. Methods that use the synchronized adornment are called synchronous methods. When a thread a executes this synchronous method, the other threads attempting to invoke the synchronization method must wait until thread a exits the synchronization method.

class MyThread implements runnable{

private int count=0; Define shared variables Count

public void Run () {

Test ();

}

Private synchronized void Test () {

for (int i=0; i<5; i++) {

count++;

Thread.yield ();

count--;

System.out.print (count+ ",");

}

}

}

public class threadexample{

public static void Main (string[] args) throws interruptedexception{

MyThread MyThread = new MyThread ();

thread T1 = new Thread (myThread);

Thread t2 = new Thread (myThread);

T1.start ();

T2.start ();

}

}

The added lock is automatically released when the synchronized-modified method finishes or an exception occurs.

You can use the Wait () method in a synchronous method when the synchronization method used by a thread uses a variable that needs to be modified by another thread to meet the needs of this thread. Use the Wait () method to break the execution of the method, allow this thread to wait, temporarily give up the use of the CPU resources, and allow other threads to use this synchronization method. If another thread does not need to wait while using this synchronization method, it should use the Notifyall () method to notify all the waiting threads that are waiting after using this synchronization method. Threads that have been interrupted will continue to execute this synchronization method from the break and follow the principle of "first break first". If you use the Notify () method, only the first waiting thread is notified that the wait is over.

Java Learning Notes-11th chapter multithreading mechanism

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.