Java Multithreading detailed summary _java

Source: Internet
Author: User
Tags instance method thread class

The difference between Thread.Start () and Thread.run ()

Start a thread by invoking the start () method of the thread class, at which point the thread is in a ready state and is not running. This thread class then invokes method run () to complete its operation, where method run () is called the thread body, which contains the contents of the thread to be executed, the Run method ends, the thread terminates, and the CPU runs another thread.

And if you use the Run method directly, this is only a call to a method, the program still only "main thread" this one of the threads, and did not open a new thread, its program execution path or only one, so that no write thread to achieve the purpose.

The test code is as follows

Copy Code code as follows:

public class Mythread implements Runnable {
public void Run () {
System.err.println (Thread.CurrentThread (). GetName ());
}
public static void Main (string[] args) {
Mythread thread = new Mythread ();
thread T1 = new Thread (thread, "Thread-1");
Thread t2 = new Thread (thread, "Thread-2");
T1.run ();
T2.run ();
}
}



Output results are

>> Current process is: main

>> Current process is: main

Instead, use the Start method:

Copy Code code as follows:

Package thread;
public class Mythread implements Runnable {
public void Run () {
System.err.println (">> Current process is:" +thread.currentthread (). GetName ());
}
public static void Main (string[] args) {
Mythread thread = new Mythread ();
thread T1 = new Thread (thread, "Thread-1");
Thread t2 = new Thread (thread, "Thread-2");
T1.start ();
T2.start ();
}
}



The results are:

>> Current process is: Thread-1

>> Current process is: Thread-2

Second, Threadlocal class detailed

Threadlocal is easy to words too literally, assuming that it is a "local thread". In fact, threadlocal is not a thread, but a local variable of thread, perhaps naming it as threadlocalvariable is easier to understand. When using threadlocal to maintain a variable, threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently alter its own copy without affecting the counterpart of the other thread.

The following are key points for thread-local variables (ThreadLocal variables):

A thread-local variable (ThreadLocal variables) conveniently provides a separate variable for each thread. This variable can be unaffected when multiple threads manipulate it, because each thread is actually manipulating a copy of the amount of change. Threadlocal instances typically appear in a class as static private (private static) fields that are used to correlate threads. When multiple threads access the threadlocal instance, each thread maintains a separate copy of the variable provided by threadlocal.

The following is a test code for testing: Three threads acting on an object manipulate the same Threadloacl object (integer type) to see if dirty reads occur:

Copy Code code as follows:

public class Test implements Runnable {
private static threadlocal<integer> num = new threadlocal<integer> ();
public void Run () {
Num.set (0);
for (int i = 0; i < 3; i++) {
Num.set (Num.get () + 1);
System.out.println (Thread.CurrentThread (). GetName () + ": num="
+ Num.get ());
}
}
public static void Main (string[] args) {
Test test = new test ();
thread T1 = new Thread (test, "Thread-1");
Thread t2 = new Thread (test, "Thread-2");
thread t3 = new Thread (test, "Thread-3");
T1.start ();
T2.start ();
T3.start ();
}
}



The results of the operation are as follows:

Thread-3:num=1
Thread-2:num=1
Thread-1:num=1
thread-2:num=2
thread-3:num=2
Thread-2:num=3
thread-1:num=2
Thread-1:num=3
Thread-3:num=3

As you can see from the above, there is no such phenomenon as dirty reading, so threadlocal thread safety.

Common use: When the DAO class is a single instance class, the database link (connection) is maintained independently by each thread.

Can be used to control the creation and use of sessions, as follows threadlocal<session> session = new threadlocal<session> ();

Comparison of Threadloacal and synchronization mechanisms:

1, in the synchronization mechanism, through the lock mechanism of the object to ensure that the same time only one thread access variables. At this time the variable is shared by multiple threads, using the synchronization mechanism requires the program to carefully analyze when to read and write variables, when the need to lock an object, when the release of object locks and other complex problems, programming and writing difficulty is relatively large.

2, and threadlocal from another angle to solve the multithreading of concurrent access. Threadlocal provides a separate copy of the variable for each thread, isolating multiple threads from accessing the data. Because each thread has its own copy of the variable, there is no need to synchronize the variable. Threadlocal provides a thread-safe shared object that can encapsulate unsafe variables into threadlocal when writing multithreaded code.

3, to sum up, for multi-threaded resource sharing problem, synchronization mechanism adopted the "time for space" approach, and threadlocal adopted the "space to change the time" approach. The former provides only one variable, allowing different threads to be queued for access, and the latter provides a variable for each thread so that it can be accessed simultaneously without affecting each other.

Iii. invalidmonitorstateexception Anomaly

When you call any of the methods in Wait ()/notify ()/notifyall (), if the current thread does not get a lock on the object, the Illegalmonitorstateexception exception is thrown ( This means that the program still tries to invoke wait ()/notify ()/notifyall () when no synchronized block or synchronization method is executed for the object. Because the exception is a runtimeexcpetion subclass, the exception is not necessarily captured (although you can capture as long as you wish). As a runtimeexception, such exceptions are not in wait (), notify (), Notifyall () The method signature is mentioned.

The following code, where the underlined part occurs, because no synchronization is performed on the object.

Copy Code code as follows:



public class Common implements Runnable {


Public synchronized void Method1 () throws Interruptedexception {


Thread.Sleep (1000);


System.out.println ("Method 1 called");


Thread.Sleep (1000);


System.out.println ("Method 1 Done");


}


Public synchronized void Method2 () throws Interruptedexception {


Thread.Sleep (1000);


System.err.println ("Method 2 called");


Thread.Sleep (1000);


System.err.println ("Method 2 Done");


}


public void Run () {


System.out.println ("Running" + thread.currentthread (). GetName ());


try {


if (Thread.CurrentThread (). GetName (). Equals ("Thread-1")) {


This.wait (1000);


Method1 ();


} else {


Method2 ();


Notifyall ();


}


catch (Exception e) {


E.printstacktrace ();


}


}


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


Common C = new Common ();


thread T1 = new Thread (c, "Thread-1");


Thread t2 = new Thread (c, "Thread-2");


T1.start ();


T2.start ();


}


}





Instead of the code, the underlined part:


Copy Code code as follows:



public class Common implements Runnable {


Public synchronized void Method1 () throws Interruptedexception {


Thread.Sleep (1000);


System.out.println ("Method 1 called");


Thread.Sleep (1000);


System.out.println ("Method 1 Done");


}


Public synchronized void Method2 () throws Interruptedexception {


Thread.Sleep (1000);


System.err.println ("Method 2 called");


Thread.Sleep (1000);


System.err.println ("Method 2 Done");


}


public void Run () {


System.out.println ("Running" + thread.currentthread (). GetName ());


try {


if (Thread.CurrentThread (). GetName (). Equals ("Thread-1")) {


Synchronized (this) {


This.wait (1000);


}


Method1 ();


} else {


Method2 ();


Synchronized (this) {


Notifyall ();


}


}


catch (Exception e) {


E.printstacktrace ();


}


}


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


Common C = new Common ();


thread T1 = new Thread (c, "Thread-1");


Thread t2 = new Thread (c, "Thread-2");


T1.start ();


T2.start ();


}


}





Iv. difference between sleep () and wait () and suspend ( )

Difference One:

Sleep is the thread class method that threads use to control their own processes, such as having a thread to tell the time, printing out a moment in each second, and then I need to add a single call to the Print method to perform it every second. It's like an alarm clock. Sleep () instructs the current thread to suspend execution for a specified time, giving the execution an opportunity to another thread, but the monitoring State remains and automatically recovers after that time. Calling sleep does not release object locks.

Wait is a method of the object class, used for communication between threads, which causes the thread that currently owns the lock of the object to await until another thread wakes up when the Notify method is invoked, but you can also give it a time to wake up automatically. This method is mainly used in scheduling between different threads. The object calls the Wait () method, which causes this thread to discard the object lock, enter the waiting lock pool for this object, and only after the Notify method (or Notifyall) is emitted for this object does this thread enter the object lock pool ready to get the object lock into the running state.

Difference Two:

Calling the wait method frees the current thread's locks, but the communication between threads is managed by objects, and all threads that manipulate an object are managed by their own wait method. As if this object is a television, three people are three threads, then the TV remote control is this lock, if now a holding the remote control, TV call wait method, then a will hand over the remote control, by the JVM virtual machine, the remote control should be handed to WHO.

Calling the Sleep method does not release the lock because Sleep () is a thread used to manage its own methods and does not involve thread communication. Or the example above, if a for the duration of the remote control, he can use his own sleep every 10 minutes, and in his console rest 10 minutes, the remote is still in his hand, the other people can not get the remote control.

Suspend () method is prone to deadlock. When the suspend () is invoked, the target line Cheng stops, but still holds the lock acquired prior to that. At this point, no other thread can access the locked resource unless it is resumed by a "pending" thread. For any thread, if they want to restore the target thread while attempting to use any of the locked resources, it can cause a deadlock

A thread that holds a lock releases the lock in the following situations:

1. Complete the synchronization code block.

2. During the execution of the synchronized code block, an exception is encountered that causes the thread to terminate.

3. During the execution of the synchronized code block, the Wait () method of the object to which the lock belongs is executed, and the thread releases the lock and makes the waiting pool for the object.

A thread does not release a lock, although it stops executing in the following situations:

1. During the execution of the synchronized code block, the Thread.Sleep () method is executed, the current thread discards the CPU, begins to sleep, and does not release the lock during sleep.

2. During the execution of the synchronized code block, the Thread.yield () method was executed, and the current thread discards the CPU but does not release the lock.

3. During the execution of the synchronized code block, the other thread executes the suspend () method of the current object, the current thread is paused, but the lock is not released.

V. Using synchronization on static methods

Java recognizes only two types of locks: object locks and class locks.

When a static method is synchronized, the class object is obtained, so when one thread enters a synchronized static method, the thread monitor acquires the lock on the class itself, locks the entire class, and other threads cannot enter any of the static synchronization methods of the class. It is not like an instance method, because multiple threads can access different instance synchronization instance methods at the same time. The test code is as follows:

Copy Code code as follows:



public class Common implements Runnable {


Public synchronized static void Method1 () throws Interruptedexception {


Thread.Sleep (1000);


System.out.println ("Method 1 called");


Thread.Sleep (1000);


System.out.println ("Method 1 Done");


}


Public synchronized static void Method2 () throws Interruptedexception {


Thread.Sleep (1000);


System.err.println ("Method 2 called");


Thread.Sleep (1000);


System.err.println ("Method 2 Done");


}


public void Run () {


System.out.println ("Running" + thread.currentthread (). GetName ());


try {


if (Thread.CurrentThread (). GetName (). Equals ("Thread-1")) {


Method1 ();


} else {


Method2 ();


Thread.CurrentThread (). Notify ();


}


catch (Exception e) {


E.printstacktrace ();


}


}


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


The following code creates different threads on different objects to test for the same class and will not have a lock


Common C1 = new Common ();


Common C2 = new Common ();


thread T1 = new Thread (c1, "Thread-1");


Thread t2 = new Thread (c2, "Thread-2");


T1.start ();


T2.start ();


}


}





The results of the implementation are as follows:


Running Thread-2


Running Thread-1


Method 2 called


Method 2 Done


Method 1 called


Method 1 Done

Six, two threads on one object can call two different synchronous instance methods at the same time?

No, because an object has synchronized the instance method, the thread gets the object lock of the object. Therefore, you cannot perform other synchronization methods until this method frees the object lock. The test code is as follows:

Copy Code code as follows:



public class Common implements Runnable {


Public synchronized void Method1 () throws Interruptedexception {


Thread.Sleep (1000);


System.out.println ("Method 1 called");


Thread.Sleep (1000);


System.out.println ("Method 1 Done");


}


Public synchronized void Method2 () throws Interruptedexception {


Thread.Sleep (1000);


System.err.println ("Method 2 called");


Thread.Sleep (1000);


System.err.println ("Method 2 Done");


}


public void Run () {


System.out.println ("Running" + thread.currentthread (). GetName ());


try {


if (Thread.CurrentThread (). GetName (). Equals ("Thread-1")) {


Method1 ();


} else {


Method2 ();


Thread.CurrentThread (). Notify ();


}


catch (Exception e) {


E.printstacktrace ();


}


}


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


Common C = new Common ();


thread T1 = new Thread (c, "Thread-1");


Thread t2 = new Thread (c, "Thread-2");


T1.start ();


T2.start ();


The following code, as a contrast, creates different objects and is not disturbed by object locks


Common C1 = new Common ();


Common C2 = new Common ();


C1.start ();


C2.start ();


}


}





The results of the implementation are as follows:


Running Thread-1


Running Thread-2


Method 1 called


Method 1 Done


Method 2 called


Method 2 Done

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.