Multithreaded Programming in Java

Source: Internet
Author: User
Tags instance method semaphore switches throw exception

Multithreaded Programming in Java

First, the advantages and disadvantages of multithreading

Advantages of Multithreading:

1) Better Resource utilization
2) programming is easier in some cases
3) Faster program response

The cost of Multithreading:

1) more complex design
While there are several multithreaded applications that 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) 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, before it starts 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:

public class MyThread extends Thread {public   void run () {     System.out.println ("MyThread Running");}   } MyThread MyThread = new MyThread (); Mytread.start ();

You can also create an anonymous subclass of thread as follows:

Thread thread = new Thread () {public   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:

public class Myrunnable implements Runnable {public   void run () {    System.out.println ("myrunnable Running");}   } Thread thread = new Thread (new myrunnable ()); Thread.Start ();

Similarly, you can create an anonymous class that implements the Runnable interface as follows:

Runnable myrunnable = new Runnable () {public   void run () {     System.out.println ("Runnable Running");}   } Thread thread = 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:

    1. Instance method
    2. Static methods
    3. Synchronization blocks in an instance method
    4. Synchronization blocks in a static method

Instance method synchronization:

Public synchronized 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:

public static synchronized 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:

public void Add (int value) {    synchronized (this) {       This.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.

public class MyClass {public   synchronized void Log1 (string msg1, String msg2) {      Log.writeln (MSG1);      Log.writeln (MSG2);   }   public void log2 (string msg1, String msg2) {      synchronized (this) {         Log.writeln (MSG1);         Log.writeln (MSG2);      }   } }

Synchronization blocks in a static method:

public class MyClass {public    static synchronized void Log1 (string msg1, String msg2) {       Log.writeln (MSG1);       Log.writeln (MSG2);    }    public static void Log2 (String msg1, String msg2) {       synchronized (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:

public class mywaitnotify{  monitorobject mymonitorobject = new Monitorobject ();  Boolean wassignalled = false;  public void dowait () {    synchronized (mymonitorobject) {while      (!wassignalled) {        try{          Mymonitorobject.wait ();         } catch (Interruptedexception e) {...}      }      Clear signal and continue running.      wassignalled = false;    }  }  public void Donotify () {    synchronized (mymonitorobject) {      wassignalled = true;      Mymonitorobject.notify ();}}}  

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):

public class Lock {    Boolean isLocked = false;    Thread  lockedby = null;    int lockedcount = 0;    Public synchronized void Lock () throws interruptedexception{        Thread callingthread = Thread.CurrentThread ();        while (isLocked && lockedby! = callingthread) {            wait ();        }        IsLocked = true;        lockedcount++;        Lockedby = 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{    //do critical section code, which may throw exception} finally {    lock.unlock ();}

Vii. other synchronization methods in Java

Signal Volume (Semaphore): Java.util.concurrent.Semaphore

Blocking queues (Blocking queue): Java.util.concurrent.BlockingQueue

public class Blockingqueue {    private List queue = new LinkedList ();    private int limit = ten;    public blockingqueue (int limit) {        this.limit = limit;    }    Public synchronized void Enqueue (Object item) throws Interruptedexception {while        (this.queue.size () = = This.limit) {            wait ();        }        if (this.queue.size () = = 0) {            notifyall ();        }        This.queue.add (item);    }    Public synchronized Object dequeue () throws Interruptedexception {while        (this.queue.size () = = 0) {            wait (); c17/>}        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:

Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Main {public    static void Main (string[] args) {        Executorservice Cachedthreadpool = Executors.newcachedthreadpool ();        for (int i = 0; i < i++) {            final int index = i;            Cachedthreadpool.execute (New Runnable () {public                void run () {                    System.out.println (index);}}            );    }}

Multithreaded Programming in Java

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.