Java Learning Notes-8. Multithreaded programming

Source: Internet
Author: User

I. Introduction of threading

1. Multithreading and multi-process differences

(1) The granularity of the two is different, the process is managed by the operating system, while the thread is within a process

(2) Each process is the basic unit of operating system allocation resources and processor scheduling, with independent code, internal data, and state

And a process of multithreading is only the basic unit of the processor scheduling, sharing the resources of the process, there may be interaction between the threads

(3) The data of the thread itself is usually only the register data, and the stack used by a program executes, so the thread switching is less burdensome than the process switching

Class 2.Thread: Java threads are implemented by the Java.lang.Thread class, and a thread object represents a threading

3.Runnable interface: Only one method run (), all user classes that implement the Runable interface must implement the run ()

When a thread is dispatched and turned into a running state, it executes the operation defined in the run () method, so a class that implements the Runnable interface is actually the operation that defines a new thread

The thread class implements the Runnable interface

Second, the implementation of the thread

1. Implementing Multithreading: Inheriting the thread class to construct threads, implementing runnable interfaces to construct threads

2. Inherit the thread class: the Run () method in the thread class must be covered, and the code that the thread executes is defined in the run () method

Definition syntax:

class extends Thread {    attribute:    method:    // Overwrite the Run method in the Thread class public    void run () {        thread subject;    }}

Inherit the thread class to create and execute multithreaded steps:

(1) Defining a class extension thread

(2) override the Run () method, which implements the actions to be performed in the thread

(3) Create an object of this thread class

(4) Call the Start () method to start the thread object

Cases:

classCountingthreadextendsThread {PrivateString name;  PublicCountingthread (String name) { This. Name =name; }     Public voidrun () {System.out.println ("Thread Start:" + This. Name);  for(inti = 0; I < 9; i++) {System.out.println (name+ "Run:" + (i + 1) + "\ T"); } System.out.println ("Thread Finish:" + This. Name); }}classThreaddemo { Public Static voidMain (string[] args) {countingthread thread1=NewCountingthread ("Thread A"); Countingthread thread2=NewCountingthread ("Thread B");        Thread1.start ();    Thread2.start (); }}

The reason for the run () method cannot be called directly: when the start () method is called, the system starts the thread and assigns the virtual CPU to start executing the run () method of the thread, returning immediately instead of waiting until the run () method executes.

3. Implement the Runnable interface

(1) Define a class implementation Runnable interface: Implements Runnable

(2) overwrite the Run () method

(3) Creating an object for the Runnable interface implementation class

(4) Creating an object of the thread class (with the Runnable subclass object as the constructor method parameter)

(5) Start the thread with the start () method

Cases:

classCountingthreadImplementsRunnable {PrivateString name;  PublicCountingthread (String name) { This. Name =name; }     Public voidrun () {System.out.println ("Thread Start:" + This. Name);  for(inti = 0; I < 10; i++) {System.out.println (name+ "RUN:I =" +i); } System.out.println ("Thread End:" + This. Name); }} Public classRunnabledemo { Public Static voidMain (string[] args) {countingthread ct1=NewCountingthread ("Thread A"); Countingthread Ct2=NewCountingthread ("Thread B"); Thread Thread1=NewThread (CT1); Thread thread2=NewThread (CT2);        Thread1.start ();    Thread2.start (); }}

4. Comparison of two ways to achieve

(1) using the Runnable interface, you can avoid the limitations of Java single inheritance

(2) Implementation of the Runnable interface for multiple threads of the same program code to handle the same resource

Therefore, it is recommended to use runnable interface to implement multithreading in development

Third, the scheduling of the thread

1. Thread Life cycle

(1) New status: Thread MyThread = new Mythreadclass ()

When a thread is in the new state, it is simply an empty thread object and the system does not allocate resources for it

(2) Ready state: Also becomes operational status (Runnable), Method: Start ()

After a thread in the new state is started, the thread queue is queued for CPU time slices

At this point, it already has the conditions of operation, once it comes to enjoy the CPU resources, you can separate from the main thread that created it to start its own life cycle

(3) Running state: When the ready state of the thread is dispatched and the processor resource is obtained, it goes into a running state

When a thread object is scheduled to execute, it automatically calls the run () method of this object and executes it sequentially

(4) Blocking state: An executing thread if in some special cases, the state of the thread cannot be executed, the CPU will be conceded

(5) Death status: A normal running thread completes all work, that is, the last statement of the run () method is executed

Or thread is forced to execute prematurely, such as terminating a thread by executing the Stop () method

2. Priority of Thread: Java divides the priority of a thread into 10 levels, denoted by 1~10, the higher the number, the greater the level

Static constants in the thread class:

Defined Describe The constant represented
public static final int min_priority Lowest priority level 1
public static final int norm_priority Normal priority, default priority 5
public static final int max_priority Highest priority level 10

Method: setpriority (int p): Change the priority of a thread

GetPriority (): Gets the priority of the thread

Higher-priority threads get more running opportunities

Four, the basic control of the thread

1. Thread sleep: public static void Sleep (long Millis) throws Interruptedexception

The current thread will sleep Millis milliseconds, allowing the thread with low priority to get the chance to execute

2. Thread Status test:

The thread is active after it is started by the start () method until it is terminated at any time

You can obtain whether a thread is active by using the IsAlive () method in thread

Definition: Public Final Boolean isAlive ()

3. Thread join: Public final void Join () throws Interruptedexception

There is an a thread running, you want to insert a B thread, and ask the B thread to finish before continuing A's execution

4. Thread comity: public static void Yield ()

You cannot specify how long to pause, the CPU will be handed over to a thread with the same priority, or the original thread will continue to run

Note: Only threads with the same priority have an opportunity to execute

5. Daemon Thread: Not a core part of the application, when all non-daemons of an application terminate the run, the application will terminate even if there is still a daemon thread running

A daemon thread is typically used to service other threads in the background

Method: Public Final Boolean Isdaemon () determines whether a thread is a daemon thread

Public final void Setdaemon () Cheng a line as a daemon thread

Five, multi-threaded synchronization and deadlock

1. Object mutex: Prevents multiple threads from accessing a condition variable at the same time, using synchronized to declare a block of code or a method that operates on shared data

(1) Synchronizing code blocks: Only one thread can gain access to this code block at any time

Synchronized (< Sync object name >) {

< code that needs to be synchronized >

}

(2) Synchronization method: Any time the method can only be executed by one thread

Synchronized < method return value type > < method name > (< parameter list >) {

< method body >

}

2. Interactive synchronization between threads

Wait for notification mechanism: (1) Before producers do not produce, inform consumers to wait, producer production, immediately notify consumers of consumption

(2) After consumer consumption, inform the producer has finished consuming, need to produce

Method:

Method name Describe
Public final void Wait () throws Interruptedexception Release the lock you have held and enter the waiting queue
Public final void Wait (long timeout) throws Interruptedexception Specify the maximum wait time, in milliseconds
Public final void Notify () Wakes the first waiting thread and moves it into the lock request queue
Public final void Notifyall () Wake up all waiting threads and move them into the lock request queue

Attention:

Wait () and notify ()/notifyal () must be executed with the lock already held, they can only appear within the scope of the synchronized action

Java Learning Notes-8. Multithreaded programming

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.