Original http://www.cnblogs.com/luxiaoxun/
First, the advantages and disadvantages of multithreading
Advantages of Multithreading:
1) better resource Utilization 2) programming is simpler in some cases 3) program responds faster
The cost of Multithreading:
1) more complex design Although some multithreaded applications are simpler than single-threaded applications, others are generally more complex. This part of the code requires special attention when accessing shared data in multi-threaded access. The interaction between threads is often very complex. Incorrect thread synchronization produces errors that are very difficult to discover and reproduce to fix.
2) The cost of context switching when the CPU switches from executing a thread to executing another thread, it needs to store the local data of the current thread, the program pointer, and so on, then load the local data of the other thread, the program pointer, and so on, and finally start executing. This switchover is called a "context switch". The CPU executes one thread in one context and then switches to another in the context of executing another thread. Context switching is not cheap. If it is not necessary, you should reduce the occurrence of context switches.
Second, create Java multithreading
1. Create a subclass of thread
Creating an instance of the thread subclass and overriding the Run method, the Run method is executed after the start () method is called. Examples are as follows:
Extends Thread { void run () {System.out.println ("MyThread running"new MyThread (); Mytread.start ();
You can also create an anonymous subclass of thread as follows:
New Thread () { void run () { System.out.println ("Thread Running");}}; Thread.Start ();
2. Implement Runnable interface
The second way to write thread execution code is to create an instance of a class that implements the Java.lang.Runnable interface, and the methods in the instance can be called by the thread. Here's an example:
Implements Runnable { void run () {System.out.println ("myrunnable running"new Thread (new myrunnable ()); Thread.Start ();
Similarly, you can create an anonymous class that implements the Runnable interface as follows:
New Runnable () { void run () { System.out.println ("Runnable running"new Thread (myrunnable ); Thread.Start ();
Third, thread safety
Running multiple threads in the same program itself does not cause problems, and the problem is that multiple threads access the same resources. Like a memory area (variable, array, or object), System (database, Web services, etc.) or file. In fact, these problems can occur only if one or more threads write to these resources, and as long as the resources do not change, it is safe for multiple threads to read the same resource.
When two threads compete for the same resource, a race condition is called if the order of access to the resource is sensitive. The code area that causes the race condition to occur is called the critical section.
If a resource is created, used, destroyed in the same thread, and never out of control of that thread, the use of that resource is thread-safe.
Iv. Java synchronization blocks
Synchronization blocks in Java are marked with synchronized. Synchronization blocks are synchronized on an object in Java. All synchronized blocks that are synchronized on an object can only be entered by one thread at a time and perform operations. All other threads waiting to enter the synchronization block will be blocked until the thread that executes the synchronization block exits.
There are four different types of synchronization blocks:
- Instance method
- Static methods
- Synchronization blocks in an instance method
- Synchronization blocks in a static method
Instance method synchronization:
void Add (int value) {This.count + = value;}
The Java instance method synchronization is synchronous on the object that owns the method. In this way, each instance's method synchronization is synchronized on a different object, that is, the instance to which the method belongs. Only one thread can run in the instance method synchronization block. If more than one instance exists, a thread can perform operations in one instance synchronization block at a time. One instance of a thread.
static method synchronization:
void Add (int value) {count + = value;}
Synchronization of static methods refers to synchronizing on the class object on which the method resides. Because a class can only correspond to one class object in a Java virtual machine, it allows only one thread to execute a static synchronization method in the same class.
Synchronization blocks in an instance method:
void Add (int value) { synchronized (thisthis.count + = value;}}
Note the Java synchronization block constructor encloses the object with parentheses. In the example above, "This" is used, which is called the instance itself of the Add method. Objects enclosed in parentheses in the synchronization constructor are called Monitor objects. The code above uses the monitor object to synchronize, and the synchronous instance method uses the instance of the calling method itself as the monitor object. Only one thread at a time can execute within a Java method synchronized to the same monitor object.
The following two examples all synchronize the instance objects they invoke, so they are equivalent to the execution effect of the synchronization.
Class MyClass { voidvoidsynchronized (this) {Log.writeln (MSG1); Log.writeln (MSG2);}}}
Synchronization blocks in a static method:
Class MyClass { voidvoidsynchronized (MyClass. Class) {Log.writeln (MSG1); Log.writeln (MSG2);}} }
These two methods do not allow simultaneous access by threads. If the second synchronization block is not synchronized on the Myclass.class object. Then both methods can be accessed by the thread at the same time.
V. Java thread Communication
The goal of thread communication is to enable threads to send signals to each other. Thread communication, on the other hand, enables threads to wait for signals from other threads.
Java has a built-in wait mechanism to allow threads to become non-operational when waiting for a signal. The Java.lang.Object class defines three methods, wait (), notify (), and Notifyall () to implement this wait mechanism.
Once a thread invokes the wait () method of any object, it becomes non-operational until another thread invokes the Notify () method of the same object. In order to call Wait () or notify (), the thread must first obtain the lock on that object. In other words, the thread must call Wait () or notify () in the synchronization block.
The following is a shared object that uses the Wait () and notify () to implement inter-thread communication:
PublicClassmywaitnotify{Monitorobject Mymonitorobject =NewMonitorobject ();Boolean wassignalled =False;PublicvoidDowait () {synchronized (Mymonitorobject) { while (! wassignalled) {try{mymonitorobject.wait ();} catch (Interruptedexception e) {...}} //clear signal and continue running. wassignalled = falsepublic void Donotify () {synchronized (mymonitorobject) {wassignalled = true
Note the following points:
1. Wait () and notify () are called in the synchronization block, either by waiting for the thread or by the wake-up thread. This is mandatory! A thread cannot call wait (), notify (), or notifyall () if it does not hold an object lock. Otherwise, a Illegalmonitorstateexception exception is thrown.
2. Once the thread invokes the Wait () method, it releases the lock on the monitor object it holds. This will allow other threads to also call Wait () or notify ().
3. In order to avoid losing signals, they must be kept in the signal class. such as the wassignalled variable above.
4. False wakeup: Because of inexplicable reasons, threads may wake up without calling Notify () and Notifyall (). This is called false wakeup (spurious wakeups). To prevent false wakeup, the member variable that holds the signal is examined in a while loop, not in the IF expression. Such a while loop is called a spin lock.
5. Do not call wait () in a string constant or global object. That is, the above monitorobject cannot be a string constant or a global object. Each instance of mywaitnotify has a monitor object that belongs to it, instead of calling Wait ()/notify () on an empty string.
Six, the lock in Java
Starting with Java 5, the Java.util.concurrent.locks package contains the implementation of some locks, so you don't have to implement your own locks.
Some of the commonly used locks:
Java.util.concurrent.locks.Lock; Java.util.concurrent.locks.ReentrantLock; Java.util.concurrent.locks.ReadWriteLock; Java.util.concurrent.locks.ReentrantReadWriteLock;
A simple implementation of a reentrant lock (reentrant Lock):
PublicClassLock {Boolean isLocked =False; Thread Lockedby =Null;int lockedcount = 0;PublicSynchronizedvoid Lock ()Throwsinterruptedexception{Thread Callingthread =Thread.CurrentThread ();While (isLocked && lockedby! = callingthread) {wait ();} isLocked = true; lockedcount++; Locke DBy = Callingthread;} public synchronized void unlock () { if (thread.currentthread () = = This . Lockedby) { lockedcount--; if (Lockedcount = = 0) {isLocked = false; notify (); }}}
Note: Call unlock () in the Finally statement
Lock.lock (); try{ //finally {lock.unlock ();}
Vii. other synchronization methods in Java
Signal Volume (Semaphore): Java.util.concurrent.Semaphore
Blocking queues (Blocking queue): Java.util.concurrent.BlockingQueue
PublicClassBlockingqueue {Private List queue =NewLinkedList ();Privateint limit = 10;Public Blockingqueue (IntLimit) {This.limit =Limit }PublicSynchronizedvoid Enqueue (Object item)Throwsinterruptedexception {while (This.queue.size () = =This. limit) {wait ();}if (this.queue.size () = = 0 this.queue.add (item);} public synchronized Object dequeue () throws Interruptedexception {while (this.queue.size () = = 0) {wait ();} if (this.queue.size () = = this.limit) {Notifyall ();} return this.queue.remove (0 ); }}
Viii. thread Pool in Java
Java provides four thread pools through executors, namely:
Newcachedthreadpool
Creates a cacheable pool of threads. If the size of the thread pool exceeds the thread required to process the task, then a partially idle (60 second non-performing task) thread is reclaimed, and when the number of tasks increases, the thread pool can intelligently add new threads to handle the task. This thread pool does not limit the size of the thread pool, and the thread pool size is entirely dependent on the maximum thread size that the operating system (or JVM) can create.
Newfixedthreadpool
Creates a fixed-size thread pool. Each time a task is committed, a thread is created until the thread reaches the maximum size of the threads pool. Once the maximum size of the thread pool is reached, the thread pool will be replenished with a new thread if it ends up executing an exception.
Newscheduledthreadpool
Create a thread pool of unlimited size. This thread pool supports timing and periodic execution of tasks.
Newsinglethreadexecutor
Creates a single threaded pool of threads. This thread pool supports timing and periodic execution of tasks. This thread pool has only one thread at work, which is equivalent to single-threaded serial execution of all tasks. If this unique thread ends because of an exception, a new thread will replace it. This thread pool guarantees that the order in which all tasks are executed is performed in the order in which the tasks are submitted.
Thread pool Simple usage:
ImportJava.util.concurrent.ExecutorService;ImportJava.util.concurrent.Executors;public class Main { Span style= "color: #0000ff;" >public static void Executors.newcachedthreadpool (); for (int i = 0; i <; i++ final int index =< Span style= "color: #000000;" > I; Cachedthreadpool.execute (new Runnable () {public void run () {System.out.println (index);}}); } }}
Java multithreaded programming