Java multithreading Basics

Source: Internet
Author: User
The Java language has built-in multithreading. Supported All classes that implement the runnable interface can start a new thread. The new thread will execute the run () method of the instance. After the run () method is executed, the thread ends.

Once a thread is executed, the instance cannot be restarted. You can only generate a new instance and start a new thread.

 

The thread class is an instance that implements the runnable interface and represents a thread instance. The only way to start a thread is through the START () instance method of the thread class:

Thread t = new thread ();
T. Start ();

The START () method is a native method that starts a new thread and runs the run () method. The default run () method of the thread class exits without doing anything. Note: directly calling the run () method does not start a new thread. Java There is no difference between methods.

Therefore, there are two ways to implement your own thread:

Method 1: your own extend Thread class, and re-write the run () method, you can start a new thread and execute your own defined run () method. For example:

Public class mythread extends thread {
Public run (){
System. Out. println ("mythread. Run ()");
}
}

Start the thread in the appropriate place: New mythread (). Start ();

Method 2: If your class has extends another class, you cannot directly extends thread. At this time, you must implement a runnable interface:

Public class mythread extends otherclass implements runnable {
Public run (){
System. Out. println ("mythread. Run ()");
}
}

To start mythread, you must first instantiate a thread and input your own mythread instance:

Mythread MYT = new mythread ();
Thread t = new thread (MYT );
T. Start ();

In fact, after passing in a runnable target parameter to the thread, the thread's run () method will call target. Run (). Refer to the JDK source code:

Public void run (){
If (target! = NULL ){
Target. Run ();
}
}

The thread also has some settings such as name, threadgroup, and isdaemon. Mode There are very few associations. I will not talk about them here.

Thread Synchronization

Because multiple threads in the same process share memory space, in Java, it is a shared instance. When multiple threads attempt to modify the content of an instance at the same time, a conflict occurs, threads must implement shared mutex to synchronize multiple threads.

The simplest synchronization method is to mark a method as synchronized. For the same instance, only one synchronized method can be executed at any time. When a method is executing a synchronized method, if other threads want to execute any of the synchronized methods of this instance, they must wait until the thread executing the Synchronized Method exits this method, can be executed in sequence.

However, the non-synchronized method is not affected. No matter whether or not the synchronized method is executed, the non-synchronized method can be executed by multiple threads at the same time.

Note that only the synchronized methods of the same instance are the same. Time It can only be executed by one thread, and the synchronized methods of different instances can be concurrent. For example, if Class A defines the Synchronized Method sync (), different instances of a1.sync () and a2.sync () can be executed by two threads at the same time.

Java Lock Mechanism

The implementation of multi-thread synchronization ultimately depends on the lock mechanism. We can imagine that a shared resource is a room and everyone is a thread. When a wants to enter the room, he must get the door lock. Once a gets the door lock, he will immediately lock the door after entering, so B, c, d... you have to wait outside the door until a releases the lock, B, c, d... one of them grabbed the lock (the specific method depends on the implementation of JVM, You can first come, first served, or randomly selected), then entered the room and locked the door. In this way, at most one person can be in the House (using shared resources) at any time ).

Java language specifications have built-in support for multithreading. For Java Program For example, every object instance has a "Lock". Once a thread acquires the lock, if other threads want to obtain the lock, they can only wait after the thread releases the lock. There is only one way to obtain the lock, that is, the synchronized keyword. For example:

Public class sharedresource {
Private int COUNT = 0;

Public int getcount () {return count ;}

PublicSynchronizedVoid setcount (INT count) {This. Count = count ;}

}

Synchronization Method public synchronized void setcount (INT count) {This. Count = count;} is actually equivalent:

Public void setcount (INT count ){
Synchronized (this) {// obtain this lock here
This. Count = count;

} // Release this lock here
}

The red part indicates the code segment to be synchronized. This area is a "dangerous area". If two or more threads run simultaneously, a conflict occurs. Therefore, you need to change the internal status of sharedresource, you must first obtain the lock of the sharedresource instance.

When the synchronized block is exited, the lock owned by the thread is automatically released, so other threads can obtain the lock again.

To improve performance, you do not have to lock this. For example, sharedresource has two independent variables:

Public class sharedresouce {
Private int A = 0;
Private int B = 0;

Public synchronized void Seta (int A) {This. A = ;}

Public synchronized void SETB (int B) {This. B = B ;}
}

If the entire method is synchronized, SETB () and SETB () cannot be synchronized during Seta (). To improve performance, you can Use Lock of different objects:

Public class sharedresouce {
Private int A = 0;
Private int B = 0;
Private object sync_a = new object ();
Private object sync_ B = new object ();

Public void Seta (int ){
Synchronized (sync_a ){
This. A =;
}
}

Public synchronized void SETB (int B ){
Synchronized (sync_ B ){
This. B = B;
}
}
}

 

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.