Java advanced 05 multithreading Python multithreading and synchronization Linux multithreading and Synchronization

Source: Internet
Author: User

Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!

 

Multithreading

Multithreading(Multiple thread) Is a way for computers to implement multi-task parallel processing.

In the case of a single thread, a control exists in the computer and commands are executed in sequence. A single thread seems to be a team with only one team leader. The whole team can only execute one task at a time.

Single thread

 

In a multi-thread scenario, a computer has multiple control permissions. Multiple controls can be performed at the same time, and each control can execute a series of commands in sequence. Multithreading seems to be a team member who executes different tasks at the same time.

Refer to Linux multithreading and synchronization, and Compare Python multithreading and synchronization.

Multithreading

Traditionally, multithreading is a function provided by the operating system. For single-core CPUs, only one thread exists in the hardware. Under the control of the operating system, the CPU will switch between different tasks (threads), resulting in multi-task synchronization. This is a single CPUTime-sharingMechanism. Now, with the development of new hardware technologies, the hardware itself began to provide multi-threaded support, such as multi-core and super-thread technologies. However, the multithreading of hardware still needs to be managed in a unified manner by the operating system. Multithreading on the Operating SystemProgramStill common.

Multiple Threads can coexist in the same process space. In a JVM process spaceStack)Indicates the order of method calls. For multithreadingMultiple stacksTo record the call sequence of different threads. Multiple stacks do not affect each other, but all threadsObjects in the shared heap.

 

Create thread

In Java, "Everything is an object", and the thread is encapsulated into an object. We can useInherit Thread classTo create a thread. TheRun ()The method contains the commands that the thread should execute. We override this method in the prepare class to explain the task to the thread:

 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 Newthread Extends  Thread {  Private   Static   Int Threadid = 0; //  Shared by all      /**  * Constructor  */      Public  Newthread (){  Super ("ID:" + (++Threadid ));}  /**  * Convert object to string  */      Public  String tostring (){  Return   Super  . Getname ();}  /**  * What does the thread do?  */      Public   Void  Run () {system. Out. println ( This  );}} 

(++ Is the accumulate operator in Java, that is, add 1 to the variable. Before threadid, add threadid to 1 and evaluate the surrounding expression.

Tostring is the method of the object root class. We can overwrite this method to convert the object into a string. When we print this object, Java will automatically call this method .)

 

We can see thatBuild Method(Super () can receive a string as a parameter. This string is the name of the thread and usesGetname ().

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

We callStart ()Method to start the thread. The START () method can be called in the constructor. In this way, once we useNewCreate a thread object and execute it immediately.

 

The thread class also provides the following common methods:

Join (thread TR)Wait for the thread tr to complete

Setdaemon ()Set the current thread to daemon in the background (Process Termination is not affected by the daemon thread)

Thread class official documentation: http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html

 

Runnable

MultithreadingAnother methodYesRunnableInterface, and provides the run () method. The advantage of implementing interfaces is that it is easy to implement multiple inheritance ). However, because of the internal class syntax, inheriting the thread creation thread can implement similar functions. Here is a simple example without going into depth:

 

 Public   Class  Test {  Public   Static   Void  Main (string [] ARGs) {thread thread1 = New Thread (New Newthread (), "first" ); Thread thread2 = New Thread ( New Newthread (), "second" ); Thread1.start ();  //  Start thread1 Thread2.start (); //  Start thread2  }}  /**  * Create new thread by implementing runnable  */ Class Newthread Implements  Runnable {  /**  * Convert object to string  */      Public  String tostring (){  Return  Thread. currentthread (). getname ();}  /**  * What does the thread do?  */      Public   Void Run () {system. Out. println (  This  );}} 

 

Synchronized

Multi-task programming is difficult to share resources. For multiple threads in the same process space, they all share objects in the heap. Operations on objects by a thread will affect other threads.

Avoid multiple threadsRacing Condition)That is, the running result depends on the execution sequence of different threads. Threads are executed concurrently and the thread sequence cannot be determined. Therefore, there should be no competition conditions in our program.

However, when multiple tasks share resources, it is easy to create competition conditions. We need to linearly execute multiple threads that share resources and cause competition conditions, that is, only one thread can be executed at a time.

(For more information, see Linux multithreading and synchronization)

 

The following is a ticket sales program. Three ticket kiosks sell 100 tickets (reservoir) together ). Each ticket kiosk must first determine whether there are more than one ticket, and then sell another ticket. If there is only one ticket left, and the ticket is sold between the judgment of a ticket kiosk and the action of selling the ticket, then the first ticket kiosk (because the ticket has been judged) it will still be sold in a tooth shape, resulting in overselling tickets. To solve this problem, there is no "gap" between the judgment and the sale ". That is to say, only after one thread completes these two actions can another thread execute them.

In JavaShare resources in an objectFor example, the following R (reservoir) object. It contains the total number of votes; operations on shared resources that may cause competition are placed inSynchronized(Synchronous)Method, such as the following sellticket (). Synchronized is the modifier of the method. In Java,The synchronized method of the same object can only be called by one thread at the same time. Other threads can only run until the call of this thread ends (one of the remaining threads. In this way, we eliminate 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 completed 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; // Restore this reservoir Private Int Count = 0; // Owned by this thread object /** * Constructor */ Public Booth (reservoir R ){ Super ("ID:" + (++ Threadid )); 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 do? */ Public Void Run (){ While ( True ){ If (This . Release. sellticket ()){ This . Count = This . Count + 1 ; System. Out. println ( This . Getname () + ": COUNTER 1" ); Try {Sleep (( Int ) Math. Random () * 100 ); // Random intervals } Catch (Interruptedexception e ){ Throw New Runtimeexception (e );}} Else { Break ;} System. Out. println ( This . Getname () + "I sold:" + Count );}}

(Math. Random ()Used to generate random numbers)

 

Every object in JavaAuto includeThere is a counter that supports synchronization and records the number of synchronized method calls. The thread obtains the counter, adds 1 to the counter, and executes the synchronized method. If other synchronized methods of the object are further called in the method, add 1 to the counter. When the synchronized method is called and exited, the counter minus 1. If other threads call the Synchronized Method of the same object, they must wait until the counter changes to 0 to lock the counter and start execution. Classes in Java are also objects (Class class objects ). Class objects also contain counters for synchronization.

 

KeyCode

Above, we used the synchronized modifier to synchronize the entire method. We can synchronize part of the code instead of the entire method. Such code is calledCritical Section). We use the following syntax:

 
Synchronized(Syncobj ){...;}

The curly braces containCode to be synchronized, Syncobj is any object. We will use the counter in the syncobj object to synchronize the code in curly brackets.

 

Welcome to continue reading the "Java quick tutorial" SeriesArticle

 

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.