java-Multi-threaded article < on >

Source: Internet
Author: User

1. Thread and Process Concepts

1.1. Process: Has a separate memory space, each independently executed program is called a process
1.2. Thread: A thread is an execution path inside a program, and a Java Virtual machine allows an application to run multiple execution threads concurrently
1.3. The difference between threads and processes
Each process has a separate code and data space (process context), and the switching overhead between processes is large
Threads: Threads in the same process share code and data space with little overhead for thread switching
Multi-process: multiple tasks (Programs) can be run concurrently in the operating system
Multithreading: Executing multiple execution paths concurrently in the same application

2. Creating and starting a thread

First: Inherit the thread class, overriding the Run method

Second: Implementing the Runnable interface, overriding the Run method

3. Comparison of two ways to create
3.1 Using the Runnable interface
Can also inherit from other classes;
Maintain the consistency of the program style.
3.2 Direct inheritance of the thread class
Can no longer inherit from other classes;
Simple to write, can manipulate threads directly
When you create a thread by implementing the Runnable interface, you can provide shared data for multiple threads of the same program code.

4. Thread Summary
4.1.Java threads are implemented through the Java.lang.Thread class.
4.2. When the program starts running, the JVM generates a thread (the main thread), and the Main method (the main method) runs on that thread.
4.3. You can create a new thread by creating an instance of the thread.
A. Each thread completes its operation by means of the method run () that corresponds to a particular thread object, and the method run () is called the thread body.
B. Start a thread by calling the start () method of the thread class. The thread enters the runnable (operational) state, and it goes to the thread

Scheduler registers this thread.
C. Calling the start () method does not necessarily execute the thread immediately, as mentioned above, it just goes into runnable instead of

Running.

4.4. Each thread has a priority, an identity name, and multiple threads can synchronize. When an identity name is not specified, it is automatically generated with a

Execution of a high-priority thread takes precedence over a low-priority thread. Each thread can or cannot be marked as a daemon. When a thread

When you create a new object in the code that is running in Thread , the initial priority of the new thread is set to the priority of the thread being created, and

The new thread is the daemon when and only if the creation thread is the daemon thread.

4.5.Java Virtual Machine Exit scenarios

    • The Runtime method of the class was called exit , and the security manager allowed the exit operation to occur.
    • All threads that are not daemon threads have stopped running, either by returning from a call to the Run method or by throwing a propagated to

     runExceptions outside of the method

Note that you do not call the thread's run () method directly in the program.

5. Basic use of threading methods

    • Static thread CurrentThread ();//Returns a reference to the currently executing thread object
    • static void yield ();//Pause the current thread for a moment.
    • static void sleep (long millis);//thread Sleep (pause execution)
    • The above three are static methods, others are generally not
    • void start ();//causes the thread to start and enter the runnable state.
    • Boolean isAlive ();//Determine if the thread is active
    • Boolean Isdaemon ();//Determine if it is a daemon thread
    • Thread.state getState ();//Returns the state of the thread
    • void SetName (String name);//Change thread name
    • void Setdaemon (Boolean on);//true is the daemon and false is the user process.

6. Scheduling of Threads

    1. Thread sleep: thread.sleep (Long Miao);//causes the thread to enter a blocking state, and enters the Ready (Runnable) state after sleep is over
    2. Thread Concession: Thread.yield ();//suspend the current thread of execution and execute the execution opportunity to the same or higher priority thread, but this time cannot be controlled. is uncertain. Just let the current thread pause for a moment.
    3. Thread join: Join ();//throws interruptedexception. The current thread calls the join method of another thread, and the current thread

Into the waiting state until the thread that calls the join () method finishes executing, and the current thread is then turned into a ready state by blocking.

4. Thread waits: The Wait () method in the object class causes the current thread to wait until another thread calls the Notify () method of this object or Notifyall

() method to wake the thread.

5. Thread Wakeup: The Notify () method of the object class, which wakes up in the. A single thread that waits on this object monitor. The choice is random. 、

The Notifyall () method of the object class wakes up all the threads waiting on this object monitor.

Note: These three methods (Wait,notify,notifyall) can only be used in methods or blocks of code that are synchronized (synchronized).

7. Thread Stop

    • If the Run method executes a recurring loop, you can provide a flag to control whether the loop executes.
    • You can use the interrupt () method when you want to stop a thread because it has entered a blocking state because the sleep () method or Wait () method was executed.

The program throws a Interruptexception exception.

    • If the program blocks because of input/output wait, it is basically necessary to wait for the input/output action to complete before leaving the blocking state. Unable to pass interrupt

method causes the thread to leave the Run method and only throws an exception if it wants to leave.

7.1 Termination of the thread

    • Natural death due to the normal exit of the Run method
    • Accidental death due to an uncaught exception terminating the Run method

8. Conversion of thread state

Create (new)---->[blocking]-----> Ready (runnable)----> Run (running)--->[blocking]----> death (Dead)

New State (new): A newly created thread object.

Ready state (Runnable): After other threads call the start method of the thread, the state of the thread is located in a running thread pool, which becomes operational and waits for

Get CPU usage. Gets the CPU and executes the program code in a ready state.

Run state (running): Executes the Run method.

Blocking state (blocked): A blocking state is temporarily stopped until a thread enters a ready state because it abandons the use of the CPU for some reason

Have the opportunity to enter the running state. There are three types of blockages:

1. Synchronous blocking: When a running thread acquires a synchronization lock on an object, the JVM puts it in the lock pool if the synchronization lock is occupied by another thread

2. Wait for blocking: When the running thread executes the wait method, the JVM puts the thread into the wait pool.

3. Other blocking: The running thread executes the sleep () method or Join () method, or when an I/O request is made, will enter the blocking state

Dead State (dead): The thread ends the life cycle when the thread finishes executing or exits the Run method due to an exception.

Note: Calling the yield () method does not enter a blocking (blocked) state

9. Adjust the priority of the thread  

Java provides a thread scheduler to monitor all threads in the program that have entered a ready state after being started. Higher-priority threads get more running opportunities

The priority of the Java thread is expressed in int, which takes the value of the three static constants of the 1~10,thread class: Max_priority=10,min_priority=1

Norm_priority=5 (the default priority value is 5).

The SetPriority (), GetPriority () method of the thread class can set and get the priority of threads

Note: High priority just gets the chance of getting the CPU a bit more

10. Thread Synchronization (Sync Lock)

In the Java language, the concept of object mutexes is introduced to ensure the integrity of shared data operations, each of which corresponds to a mutually exclusive lock

tag, this token guarantees that only one thread can access the object at any time.

The keyword synchronized is used to associate with an object mutex when an object is decorated with synchronized, indicating that the object is at any time

can only be accessed by a single thread.

Note: The parameter in the Sync Lock, synchronized (parameter), must be a reference type, such as a member variable (must be a reference class type: String)

The Member method (the return value of the method must be a reference type, not a Int,char), this (i.e. itself object), This.getclass ()//Class

11.Synchronized keywords

Synchronization code block: synchronized (this) {The code that needs to be synchronized;}

Synchronization method: Public synchronized void Method () {...}

12. Deadlock Problem

There are two threads, X and Y,x threads take the A object lock and execute code, and the y thread gets the B object lock and executes the code if the x thread

B object lock, and Y thread also to take a object lock, then everyone holding their own locks, will lead to deadlock problems.

One way to solve the deadlock is to increase the granularity of the lock.

13. Multithreading Security Issues

Multithreading security issues occur when the code in the Run () method is operating into a member variable (shared data) (thread out of sync)

Programming Tips: Try to minimize the number of member variables in the method and use local variables.

14. Thread Safety for container classes

Most container classes do not consider thread safety by default, and the program must implement its own synchronization:

A. Use synchronized to lock this object

Synchronized (list) {List.add (...);}

B. Return a synchronized container object with the Synchronizedxxx () method of the Collections class

List list=collections.synchronizedlist (New ArrayList ());

This approach is still modified with synchronized during iteration.

List List = Collections.synchronizedlist (new ArrayList ());
...
Synchronized (list) {
Iterator i = List.iterator (); while (I.hasnext ()) {foo (i.next ());}}

After JDK 5.0, a new java.util.concurrent package was added, including some container classes to ensure thread safety,

As Concurrenthashmap,copyonwritearraylist,copyonwritearrayset, they are in efficiency

And a good balance of security.

Summarize:

Wait (): Releases the CPU execution and releases the lock.

Sleep (): Releases the CPU execution and does not release the lock.

The JDK1.5 version provides some new objects that optimize the wait-to-wake mechanism.

1, replace the synchronized with the lock interface.
An implicit lock is upgraded to a display lock.
Lock
Get Lock: Lock ();
Release Lock: Unlock (); Note: The released action must be performed, so it is usually defined in the finally.
Get Condition object: newcondition ();
2, replace the Wait,notify,notifyall method in object with the await,signal,signalall of condition.
Unlike before: a synchronous code block has a lock, so it has its own independent wait and notify method.
It is now possible to encapsulate wait,notify and other methods into a unique object condition, while a lock lock can have multiple condition objects.

Some common methods in threading:
Setdaemon (Boolean): Marks a thread as a background thread, and the background thread, like the foreground thread, opens, as does the execution right,
Only at the end, there is a difference, the background thread will end automatically after the current station thread has finished running.

Join (): What do you mean? Wait for the thread to end. When a thread executes to the. Join method of B, a is frozen.
A When do you run it? When B is finished, a will be eligible to run.

Join a thread, you can complete a temporary join execution of a thread.

Note: When you start a JVM, there is a foreground thread: the main thread (which executes the Main method) and a background thread: the garbage collection mechanism thread .

java-Multi-threaded article < on >

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.