Java multithreading explanation, java Multithreading

Source: Internet
Author: User
Tags thread stop

Java multithreading explanation, java Multithreading

1. Return the name of the current Thread: Thread. currentThread. getName ();

2. The Thread name is defined by Thread + number. The number starts from 0.

3. The code to be run by the thread is stored in the run method.

4. To run a thread, it must be enabled through the method specified in the class. Start () (an execution path is added after startup)

Note: start () 1. start a thread. 2. Let the jvm call the run method.

Ii. Differences between the start () and run () methods in the Thread class

1. The thread starts a thread by calling the start () method. Then the thread is ready and runs the run method once the cpu time slice is obtained. The run method is called the thread body. It contains the content of the thread to be executed. The run () method is executed and the thread is terminated.

2. The run () method is just a common method of the class. If you call the run () method directly, the program still only has the main thread. The execution path of the program is still one, or it is executed in order.

Conclusion: The most essential function of the start () method is to apply for another thread space to execute the code in the run method. It is two lines from the current thread and runs in a relatively independent thread space. That is to say, if you directly call the run () method of the thread object, of course, it will also be executed, but it is executed in the current thread. After the run () method is executed, continue to execute the following code. after the start () method is called, the code of the run () method is executed concurrently with the current thread (single CPU) or concurrently (multiple CPUs. So remember one sentence: calling the run method of the thread object will not generate a new thread. Although the same execution result can be achieved, the execution process and execution efficiency are different.

III, The first way to create a Thread: Inherit the Thread and rewrite the run method by the subclass.

Steps:

1. The definition class inherits the Thread class;

2. The purpose is to re-write the run method and store the code to run by the thread in the run method;

3. Create a Thread object by creating a subclass object of the Thread class;

4. Call the start method of the thread, enable the thread, and execute the run method.

Thread status:
    • NEW
      Threads that have not been started are in this status.
    • RUNNABLE
      The thread being executed in the Java Virtual Machine is in this State.
    • BLOCKED
      The thread that is blocked and waiting for a monitor lock is in this status.
    • WAITING
      The thread that waits for another thread to execute a specific operation is in this State indefinitely.
    • TIMED_WAITING
      Waiting for another thread to execute depends on the operation of the specified wait time in this state.
    • TERMINATED
      The exited thread is in this status.

The second way to create a thread: Implement an interface Runnable.

Steps:

1. Define the class to implement the Runnable interface.

2. overwrite the run method in the interface (used to encapsulate the code to be run by the thread ).

3. Create a Thread object through the Thread class;

4,Pass the subclass object that implements the Runnable interface to the constructor In the Thread class as an actual parameter.

Why? The reason is that the thread object must be clear about the object to which the run method belongs.

5. Call the start method of the Thread object. Enable the thread and run the run method in the Runnable interface subclass.

Why does the Runnable interface appear?

  

1:By inheriting the Thread class, you can create multiple threads. However, this method has a limitation. If a class already has its own parent class, it cannot inherit the Thread class becauseJava single inheritance.

However, some code in this class needs to be executed by multiple threads at the same time. What should we do?

Java provides an interface Runnable only for additional function extensions of this class. This interface defines the run method. In fact, the run method is defined to store the code to be run by multiple threads.

Therefore, the second method is usually used to create a thread.

The Runnable interface can avoid the limitation of single inheritance.

2:It extracts the code that needs to be executed by multiple threads in different classes. Define the location of the Code to be run in multiple threads to an interface. It provides a prerequisite for other classes to Expand functions.

Therefore, when the Thread class describes a Thread, the internal defined run method also comes from the Runnable interface.

// Interview new Thread (new Runnable () {// anonymous public void run () {System. out. println ("runnable run") ;}} {public void run () {System. out. println ("subthread run ");}}. start (); // result: subthread run
SynchroniZed keyword (1)

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

package ths;public class Thread1 implements Runnable {public void run() {synchronized(this) {for (int i = 0; i < 5; i++) {System.out.println(Thread.currentThread().getName()+"synchronized loop " + i);}}}}
Synchronized keywords (2)

The synchronized keyword, which has two usage methods: synchronized Method and synchronized block.

1. synchronized Method: declare the synchronized Method by adding the synchronized keyword to the method declaration. For example:

Public synchronized void accessVal (int newVal );

The synchronized method controls access to class member variables: each class instance corresponds to a lock, and each synchronized method must obtain the lock of the class instance that calls the method before execution, otherwise the thread is blocked, once the method is executed, the lock is exclusive until the lock is released when the method is returned. Then, the blocked thread can obtain the lock and re-enter the executable status. This mechanism ensures that, at the same time, only one of all the member functions declared as synchronized is in the executable state (because at most only one member function can obtain the lock corresponding to this type of instance ), this effectively avoids access conflicts between class member variables (as long as all methods that may be used to invoke class member variables are declared as synchronized ).

In Java, not only are class instances, but each class also corresponds to a lock. In this way, we can declare the static member function of the class as synchronized, to control its access to static member variables of the class.

Synchronized: if a large method is declared as synchronized, the efficiency will be greatly affected. Typically, if you declare the thread-class method run () as synchronized, since the thread is always running throughout its life cycle, it will never succeed in calling any synchronized Method of this class. Of course, we can put the code of the member variable of the category class into a special method, declare it as synchronized, and call it in the main method to solve this problem, but Java provides us with a better solution, that is, the synchronized block.

2. synchronized block: Use the synchronized keyword to declare the synchronized block. Syntax:

Synchronized (syncObject ){

// Code that allows access control

}

The synchronized block is a code block in which the Code must obtain the lock of the object syncObject (as described earlier, it can be a class instance or class) before execution. The specific mechanism is described earlier. It is highly flexible because it can target any code block and can specify any locked object.

Some Understanding of synchronized (this)

1. When two concurrent threads access the synchronized (this) synchronization code block of the same object, only one thread can be executed within a time period. The other thread must wait until the current thread finishes executing this code block before executing this code block.

2. However, when a thread accesses a synchronized (this) synchronization code block of the object, the other thread can still access the non-synchronized (this) synchronization code block of the object.

3. When a thread accesses a synchronized (this) synchronization code block of the object, other threads perform synchronization on all other synchronized (this) access to the synchronization code block will be blocked.

4. The third example also applies to other synchronous code blocks. That is to say, when a thread accesses a synchronized (this) synchronization code block of an object, it obtains the object lock of this object. As a result, access by other threads to all the synchronized code parts of the object is temporarily blocked.

5. The above rules apply to other Object locks.

Principles for solving security problems:

As long as the statement for sharing data operations is completed by a thread in a certain period of time, other threads cannot come in for execution during the execution process to solve this problem.

How can we ensure thread security of shared data?

Java provides a solution: Synchronous Code block.

Format:

Synchronized (object) {// any object can be used. This object is shared data.

Code to be synchronized;

}

---------------------------------------------------------------

Synchronization:★★★★★

Benefits:Solved the thread security problem. Synchronized

Disadvantages: Relatively low performance, because the lock consumes resources, resulting in a deadlock.

The second form of synchronization:// Define synchronization for shared resources

Synchronous Functions: Actually, the synchronous keywords are defined on the function, so that the function can be synchronized.

 

Which lock is used for Synchronous functions? // Synchronized (this) is used to define a part of the code block to be synchronized.

After verification, the function has its own object this, so the lock used by the synchronous function is the this lock.This. Method Name

When the synchronization function is modified statically, Which lock is used for synchronization?

When a static function is loaded, it belongs to the class. At this time, there may not be any objects generated by this class, but the bytecode files of this class have been encapsulated into the memory. This object isObject of the class bytecode File.

So only one object exists during static loading, so this object is used by the static synchronization function.

This object isClass Name. class

What is the difference between a synchronous code block and a synchronous function?

  1. The lock used to synchronize code blocks can be any object.

2. The lock used by the synchronous function is this,

3. the lock of the static synchronization function is the bytecode file object of this class.

  Note: if there is only one synchronization in a class, you can use the synchronization function. If there are multiple syncs, you must use the synchronization code block to determine different locks. Therefore, the synchronization code block is relatively flexible.

  Wait for wake-up mechanism:Methods involved:

Wait:The synchronization thread is frozen. The execution right is released and the qualification is released. At the same time, the thread object is stored in the thread pool.

 

Notify:Wake up a waiting thread in the thread pool.

 

Policyall:All threads in the thread pool are awakened.

 

Note:

1:These methods must be defined in synchronization..

2: because these methods must mark the lock.

You need to know that the thread locked by A is wait, then this thread is equivalent to being in the thread pool of lock A and can only wake up with the slave y of lock.

3: all three methods are defined in the Object class. Why is the method of the Operation thread defined in the Object class?

Because all three methods need to define the synchronization and mark the synchronization lock to which they belong, since the lock is called, and the lock can be any object, the methods that can be called by any Object must be defined in the Object class.

Differences between wait and sleep:Analysis of these two methods: From the execution right and lock analysis:

Wait: either time or time is specified. If no time is specified, it can only be awakened by the corresponding y or notifyAll.

Sleep: the time must be specified to automatically change from frozen to running (temporary blocking ).

Wait: the thread releases the execution permission and the thread releases the lock.

Sleep: the thread releases the execution permission, but does not release the lock.

Thread stop: You can stop a thread by using the stop method. However, this method is outdated.

  

Stop thread: The principle is to end the code running the thread, that is, to end the run method.

 

How to end the run method? A loop must be defined in the general run method. So you only need to end the loop.

 

Method 1:Define the end mark of the loop.

 

Method 2: If the thread is frozen, it is impossible to read the mark.Use the interrupt method in the Thread class to forcibly clear the frozen state.. Enables the thread to restore the execution status, so that the thread can read and end with the mark.

--------- <Java. lang. Thread> ----------

Interrupt ():Interrupt thread.

SetPriority (int newPriority ):Change the thread priority.

GetPriority ():The priority of the returned thread.

ToString ():Returns the string representation of the thread, including the thread name, priority, and thread group.

Thread. yield ():Pause the currently executing thread object and execute other threads.

SetDaemon (true ):Mark this thread as a daemon thread or user thread. Mark this thread as a daemon thread or user thread. When all running threads are daemon threads, the Java Virtual Machine exits. This method must be called before the thread is started.

Join: The join method can be used when a thread is temporarily added.

When thread A executes the join method of thread B. Thread A is frozen, and execution right is released. Thread B starts execution. When will A be executed? A resumes running from frozen to running only after the end of line B.

The appearance of LOCK replaces synchronization: lock. lock ();......... Lock. unlock ();

  

Lock interface: an interface Lock interface is introduced when multiple threads upgrade to JDK.

To solve the thread security problem, use the synchronous form (Synchronous Code block or synchronous function). In fact, the lock mechanism is used eventually.

In later versions, the lock is directly encapsulated into an object. When a thread enters synchronization, the lock is obtained. When the thread finishes execution and leaves synchronization, the lock is released.

In the later analysis of the lock, it is found that the action of obtaining or releasing the lock should be more clear about the lock. Therefore, these actions are defined in the lock and the lock is defined as an object.

SoSynchronization is a hidden Lock operation, while the Lock object is a displayed Lock operation.It replaces synchronization.

In earlier versions, wait, policy, and policyall methods in the Object class were used. That is because the lock in synchronization is any Object, so the methods for waiting to wake up the operation lock are defined in the Object class.

 

The Lock specifies the object Lock. Therefore, you need to use the Lock interface to find and wait for the wake-up mechanism. The Lock interface does not directly operate on Methods waiting for wake-up, but encapsulates these methods into an object separately. This Object is Condition, which encapsulates the three methods in the Object separately. Await (), signal (), and signalAll () methods with the same functions are provided to reflect the benefits of new versions of objects.

<Java. util. concurrent. locks> Condition interface: await (), signal (), signalAll ();

  

package com.spring.test;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * Created by Administrator on 2018/3/1. */class BoundedBuffer {    final Lock lock = new ReentrantLock();    final Condition notFull = lock.newCondition();    final Condition notEmpty = lock.newCondition();    final Object[] items = new Object[100];    int putptr, takeptr, count;    public void put(Object x) throws InterruptedException {        lock.lock();        try {            while (count == items.length){                notFull.await();            }            items[putptr] = x;            if (++putptr == items.length) putptr = 0;            ++count;            notEmpty.signal();        } finally {            lock.unlock();        }    }    public Object take() throws InterruptedException {        lock.lock();        try {            while (count == 0){                notEmpty.await();            }            Object x = items[takeptr];            if (++takeptr == items.length) takeptr = 0;            --count;            notFull.signal();            return x;        } finally {            lock.unlock();        }    }}

 

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.