Java Advanced Multi-threading

Source: Internet
Author: User
Tags ticket

Multithreading

Multithreading (multiple thread) is a way for a computer to multitask parallel processing.

In a single-threaded scenario, there is a control in the computer and the instructions are executed sequentially. The single thread seems to be a team with only one Captain in command, and the whole team can only perform one task at a time.

Single Thread

In multi-threaded scenarios, there are multiple controls in the computer. Multiple controls can be performed at the same time, with each control executing a series of instructions sequentially. Multithreading seems to be a team member that performs different tasks at the same time.

Multithreading

In the traditional sense, multithreading is a function provided by the operating system. For a single-core CPU, only one thread exists in the hardware. Under the control of the operating system, the CPU switches between different tasks (between threads), which results in multitasking. This is a single CPU time-sharing mechanism of multithreading. Now, with the development of new hardware technologies, the hardware itself is beginning to provide multithreading support, such as multicore and Hyper-Threading technology. However, the multithreading of hardware is to accept the unified management of the operating system. multithreaded programs on top of the operating system are still common.

Multiple threads can coexist in the same process space. In a process space in the JVM, a stack (stack) represents the order of the method calls. For multithreading, there is a need for multiple stacks in the process space to record the invocation order of different threads. Multiple stacks do not affect each other, but all the threads will share the objects in the heap (heap).

Creating Threads

In Java "Everything is Object", threads are also encapsulated as an object. We can create threads by inheriting the thread class. The run () method in the thread class contains the instructions that the thread should execute. We override this method in a derived class to explain to the thread the task to be done:

public class test{public    static void Main (string[] args)    {        Newthread thread1 = new Newthread ();        Newthread thread2 = new Newthread ();        Thread1.start (); Start Thread1        thread2.start ();//Start thread2    }}/** * Create new thread by inheriting thread */class Newthrea D extends Thread {    private static int threadID = 0;//shared by all    /**     * constructor */public    New Thread () {        super ("ID:" + (++threadid));    }    /**     * Convert object to String     *    /public string toString () {        return super.getname ();    }    /**     * What does the thread does?     *    /public void Run () {        System.out.println (this);    }}

(+ + is the additive operator in Java, which adds 1 to the variable.) Here + + appears before ThreadID, indicating that the ThreadID plus 1, and then the surrounding expression evaluation

ToString is a method of the object root class, and we can override the method to convert the object to a string. When we print the object, Java will call the method automatically. )

As you can see, the build method of the thread base class (Super ()) can receive a string as a parameter. The string is the name of the thread and is returned using GetName ().

After defining the class, we create the thread object in the main () method. Each thread object is a single thread. After the thread object is created, the thread has not started executing.

We call the start () method of the thread object to start the thread. The start () method can be called in the construction method. This way, once we use new to create the thread object, we execute it immediately.

The thread class also provides the following common methods:

Join (thread tr) waits for thread tr to complete

Setdaemon () sets the current thread as background daemon (process end is not affected by daemon thread)

Thread Class Official Document: Http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html

Runnable

Another way to implement multithreading is to implement the Runnable interface and provide the run () method. The benefit of implementing an interface is that it is easy to implement multiple inheritance (multiple inheritance). However, because of the inner class syntax, inheriting thread creation threads can implement similar functionality. Let's give a simple example below, not in depth:

public class test{public    static void Main (string[] args)    {        Thread thread1 = new Thread (new Newthread (), "Firs T ");        Thread thread2 = new Thread (new Newthread (), "second");        Thread1.start (); Start Thread1        thread2.start ();//Start thread2    }}/** * Create new thread by implementing Runnable */class NewT Hread implements Runnable {    /**     * Convert object to String     *    /public string toString () {        return Thr Ead.currentthread (). GetName ();    }    /**     * What does the thread does?     *    /public void Run () {        System.out.println (this);    }}

Synchronized

The difficult task of multitasking is to share resources with multitasking. For multiple threads in the same process space, they all share objects in the heap. The operation of a thread on an object affects other threads.

In multithreaded programming, try to avoid the competitive conditions (racing condition), that is, the running results depend on the execution of different threads successively. Threads are executed concurrently and cannot determine the order of the threads, so there should be no competitive conditions in our program.

However, when multitasking shares resources, it is easy to create competitive conditions. We need to linearly execute multiple threads that share resources and cause race conditions, that is, only one thread is allowed to execute at the same time.

(more reference to Linux multi-threading and synchronization)

Below is a ticketing procedure. 3 ticket Booths (booth) jointly sell 100 tickets (reservoir). Each ticket booth must first determine if there is a ticket, and then sell a ticket. If there is only one ticket left, between the judgment of a ticket booth and the sale of two actions, the other ticket booth sells the ticket, then the first ticket booth (which has been judged) will still sell the tooth shape, resulting in a ticket oversold. To solve this problem, there can be no "gap" between judging and selling two actions. That is, after one thread has completed these two actions, it is possible for another thread to execute.

In Java, we place shared resources in an object, such as the following R (Reservoir) object. It contains the total number of votes, and the actions for shared resources that could result in a competitive condition are placed in the synchronized (synchronous) method, such as the following Sellticket (). Synchronized is the modifier of the method. In Java, the synchronized method of the same object can be called only by one thread at a time. Other threads must wait for the thread to call the end, (the remaining thread one) to run. In this way, we exclude the possibility of competitive conditions.

In the main () method, we pass the shared resource (R object) to multiple threads:

public class test{public static void Main (string[] args) {Reservoir R = new reservoir (100);        Booth B1 = new Booth (r);        Booth b2 = new Booth (r);    Booth B3 = new Booth (r); }}/**
* Contain shared resource
*/class Reservoir {private int total; public reservoir (int t) {this.total = t; }/** * Thread safe method * Serialized access to Booth.total */public synchronized Boolean sellticket ( {if (This.total > 0) {this.total = This.total-1; return true; Successfully sell one} else {return false;//No More tickets}}}/** * Create new Thread by inheriting thread */class Booth extends thread {private static int threadID = 0;//owned by class object Private reservoir release; Sell this reservoir private int count = 0; Owned by this thread object/** * constructor */public Booth (Reservoir R) {super ("ID:" + (++thre AdID)); This.release = R; All threads share the same reservoir This.start (); }/** * Convert object to String */public string toString () {return super.getname (); }/** * What does the thread does? */public void run () {while (true) {if (This.release.sellTicket ()) {This.count = this . Count + 1; System.out.println (This.getname () + ": Sell 1"); try {sleep (int) math.random () *100); Random intervals} catch (Interruptedexception e) {throw new Runtimee Xception (e); }} else {break; }} System.out.println (This.getname () + "I sold:" + count); }}

(Math.random () for generating random numbers)

Each object in Java automatically contains a counter to support synchronization, recording the number of calls to the Synchronized method. The thread obtains the counter, the counter adds 1, and executes the synchronized method. If an additional synchronized method of the object is further called inside the method, the counter is incremented by 1. When the Synchronized method call ends and exits, the counter is reduced by 1. Other threads If you also call the Synchronized method of the same object, you must wait for the counter to become 0 to lock the counter and start execution. Classes in Java are also objects (class objects). The class object also contains counters for synchronization.

Key code

Above, we use the synchronized modifier to synchronize the entire method. We can synchronize part of the code, not the entire method. Such code is called the Key Code (critical section). We use the following syntax:

Synchronized (syncobj) {  ...;}

The curly braces contain the code that you want to synchronize, and Syncobj is an arbitrary object. We will use the counters in the Syncobj object to synchronize the code in the curly braces.

Java Advanced Multi-threading

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.