One, what is multithreading?
Obviously, a random piece of a simple small code, starting from the main method to run, the computer is a top-down serial execution program. So what if we're going to do two tasks at once? For example, when you use your browser to surf the web, you can also log on to QQ at the same time, you can also download movies ... These tasks are performed in parallel. In the task manager of the computer, you can see a running program task, which is a single process, and most of the process under a number of threads are executed simultaneously, so multithreading is actually multiple tasks at the same time execution.
Although it is multi-threaded, the CPU execution commands are still executed in one line. However, the computer CPU only one, although multi-core computer can have virtual multi-CPU technology (this is my own understanding of multi-core CPU, not enough accurate forgive me), but compared to the computer to achieve the number of threads, there is little pity. Therefore, when the multi-threaded hardware implementation, the CPU processing method is the time-sharing processing (TDMA)! )。 What do you mean by executing this thread for a period of time, executing another thread for a while, all of the executing threads are randomly getting CPU execution. CPU operation speed is amazing, so we feel that in fact, multithreading is executed concurrently.
Second, the use of multi-threading in Java, the thread class
"Everything is Object" in the Java language is an immutable theorem, the natural thread This thing also has an object to wrap. That's the thread class . This object implements a runnable interface, which is simple, just a run method.
For multi-threaded tasks, there are two ways to implement multithreading:
1. Inherit the thread class
By encapsulating the tasks that will be implemented into the object, then inheriting the thread class, writing the task method into the Run method, and starting it with the Start method in the parent thread. such as the code to open a thread as follows
PackageCom.qyz.thread; Public classThreadDemo1 { Public Static voidMain (string[] args) {Thread T1=NewDemo ("First thread")); //start () Open threadT1.start (); //output: First thread: Opened }}//An object that inherits the threadclassDemoextendsthread{ PublicDemo (String name) {//the parent class constructs a method that can give the thread a name Super(name); } //overriding the Run method@Override Public voidrun () {//Print Thread nameSystem.out.println (Thread.CurrentThread (). GetName () + ": Opened"); }}
2, through the implementation of the Runnable interface
One problem with the thread-open approach to method one is that, when a class inherits from the architecture, only some of the subclasses need to open a new thread to perform the task, but because it is single-inheritance, inheriting a subclass of a parent class is not possible to inherit the thread method, so only by implementing
Runnable method to open the thread.
1. A class implements runnable and overrides the Run method to encapsulate tasks that require a new thread implementation. 2. New Thread (Runnable target,name) object. Encapsulates the Runnable object into a thread object. 3. Turn on thread start ()
1 PackageCom.qyz.thread;2 3 Public classThreadDemo2 {4 5 Public Static voidMain (string[] args) {6Thread T1 =NewThread (NewDemo2 (), "Second thread");7 //start () Open thread8 T1.start ();9 //Output: Second thread: OpenedTen } One } A //objects that implement the Runnable interface - classDemo2Implementsrunnable{ - //overriding the Run method the @Override - Public voidrun () { - //Print Thread name -System.out.println (Thread.CurrentThread (). GetName () + ": Opened"); + } -}
Three, the synchronization problem between multithreading
Multithreading, okay? Sure, but there will be a problem to pay attention to! That's the sync problem. When multiple threads access the same object data? There are several operations commands, which would have been to wait for a thread to operate after the object, another thread to operate, but because the CPU is a random tick execution thread, it is possible that when a thread on a shared object operation to half, the CPU is tangential to another thread, resulting in unexpected output results. This is half the problem, so you need to be careful when writing code!
Case of no-sync ticket purchase
1 PackageCom.qyz.thread;2 3 Public classTickerDemo1 {4 Public Static voidMain (string[] args) {5Saleticket st =NewSaleticket ();6 //implementation of 3 threads7Thread T1 =NewThread (St, "No. 1th ticket salesman");8Thread t2 =NewThread (St, "No. 2nd ticket salesman");9Thread t3 =NewThread (St, "No. 3rd ticket salesman");Ten //Open Thread One T1.start (); A T2.start (); - T3.start (); - } the } - classSaleticketImplementsrunnable{ - //Total 100 Tickets - Private intnum = 100; + @Override - Public voidrun () { + while( This. num > 0){ A //This code is too simple, so let the thread sleep for a while, highlighting the sync problem at Try{Thread.Sleep (10);}Catch(Exception e) {} -System.out.println (Thread.CurrentThread (). GetName () + "******" + num--); - } - } -}
The No. 0 ticket that should not have appeared, the accident
Workaround: Add lock
A lock in a multi-thread is really like a door, a thread goes in, locks the door, and another thread cannot come in until the thread inside the door executes.
The implementation of the synchronization lock in Java through the keyword synchronized, there are the following methods
1, Synchronous code block, need to synchronize the command encapsulated into a code block, plus an object to do the lock can
1 classSaleticketImplementsrunnable{2 //Total 100 Tickets3 Private intnum = 100;4 //one Object object acts as a lock5 PrivateObject lock =NewObject ();6 @Override7 Public voidrun () {8 while(true){9 //Synchronous code block encapsulationTen synchronized(lock) { One if( This. num > 0){ A //This code is too simple, so let the thread sleep for a while, highlighting the sync problem - Try{Thread.Sleep (10);}Catch(Exception e) {} -System.out.println (Thread.CurrentThread (). GetName () + "******" + num--); the}Else - Break; - } - } + } -}
The output is as follows
Problem Solving!
2. Synchronization function
The function is a kind of encapsulation, the code block is also a kind of encapsulation, that can combine together? sure! That is, by using the keyword to turn the method into a synchronous function.
1 classSaleticketImplementsrunnable{2 //Total 100 Tickets3 Private intnum = 100;4 @Override5 Public voidrun () {6 while(true){7 This. Sale ();8 }9 }Ten //by encapsulating it as a synchronous function to achieve One Private synchronized voidSale () { A if( This. num > 0){ - //This code is too simple, so let the thread sleep for a while, highlighting the sync problem - Try{Thread.Sleep (10);}Catch(Exception e) {} theSystem.out.println (Thread.CurrentThread (). GetName () + "******" + num--); - } - } -}
Successfully solved!
Java multithreaded Learning (i)