Black Horse Programmer "multithreading in Java"

Source: Internet
Author: User

Multithreading in Java

First of all, before the beginning of the thread to say a problem, we know that the implementation of multi-threading principle is the CPU in different threads to do the switch operation, and a mention of multi-threading, the first thing we think of is certainly to improve the efficiency of the system, but is it true? We can see from the code of a great God blog that sometimes single-threaded runs are more efficient than multithreading:

ImportThreadingfrom TimeImportCTimeclassMyThread (Threading. Thread): Def __init__ (self, func, args, name): Threading. Thread.__init__ (self) self.name=name Self.func=func Self.args=args def run (self): print' Starting ', Self.name, ' at: ', CTime () apply (Self.func, Self.args) print Self.name,' Finished at: ', CTime () def fun1 (x): Y= 0 forI in range (x): Y+=1def fun2 (x): Y= 0 forI in range (x): Y+=1def main (): Print' Staring single thread at: ', CTime () fun1 (10000000) fun2 (10000000) Print' Finished single thread at: ', CTime () T1= MyThread (fun1, (10000000,), fun1.__name__) T2= MyThread (fun2, (10000000,), fun2.__name__) T1.start () T2.start () T1.join () t2.join () print' All done 'if__name__ = = ' __main__ ': Main ()

The running result of the program is a single-threaded than multi-threaded operation efficiency has a significant increase, but this is why? Or because the thread is executed because the CPU is doing a quick switchover between your threads, then if you are a single-core CPU then your program will not need to verify multithreading, because the switch between the various threads is performed on a single CPU, Only a dual-core or multi-core CPU can execute different threads with different CPUs to improve the efficiency of the program. Believe that a lot of people in their own computer to experiment with excessive thread execution time problem, for the results of confusion, in fact, because of your CPU reasons.

OK, here's a little question, now let's cut into the topic and talk about threads in Java. There are two ways to create a thread, one is to inherit the thread class directly and overwrite its run () method, but we know that Java only supports single inheritance, so it is difficult to implement this method if our class has a parent class. The second is to implement the Runnable interface through a declaration, then implement the Run method, and then assign an instance of the class, which, when the thread class is created, is passed and started with a parameter construct, and Runnable provides an activation method for the non-thread class. So here's the code to illustrate the second way to create a thread:

classShowImplementsRunnable {Private intnum = 100; @Override Public voidrun () { while(true) {                if(num > 0) {System.out.println (Thread.CurrentThread (). GetName ()+":"+num); Num--; } Else {                     Break; }                }    }} Public classMymain { Public Static voidMain (string[] args) {Show Show=NewShow (); Thread T=NewThread (show); Thread T1=NewThread (show); Thread T2=NewThread (show); Thread T3=NewThread (show);        T.start ();        T1.start ();        T2.start ();    T3.start (); }}

This completes four threads executing the loop at the same time until Num sees 0, but if we open his running result, we will find a very obvious problem:

This is a part of me running results, can be obviously found four times 100, then this is why? Take this code for example, when your T thread takes the CPU's execution, executes the internal run method, enters the loop to determine if condition, num>0 pass, Enter the internal code block to print out the value of NUM, but at this time, another thread T1 get the execution right, also enter the loop to determine if condition when the decision Num>0 passed, the value of Num did not change, but still print the value of num, so there are two identical values, Similarly, when there are multiple such situations, there will be multiple duplicate values, which is the thread's security problem, that is, when multiple threads operate the same variable at the same time, unpredictable results can occur. So how do you solve such a problem? This uses the synchronized (synchronous function), for the line loads lock, which is equivalent to any thread (for example, thread a), when running to this method, to check that there are no other thread B (or C, D, etc.) is using this method (or other synchronization methods of the Class), Some words wait for thread B (or C, D) that is using the Synchronized method to run this thread A, not to lock the caller, and then run directly. Maybe it's hard to understand, but let's show a modified version of the above code, and then we'll look at the results of the operation:

classShowImplementsRunnable {Private intnum = 100; Object obj=NewObject (); @Override Public voidrun () { while(true) {            synchronized(obj) {if(num > 0) {System.out.println (Thread.CurrentThread (). GetName ()+":"+num); Num--; } Else {                     Break; }            }        }    }} Public classMymain { Public Static voidMain (string[] args) {Show Show=NewShow (); Thread T=NewThread (show); Thread T1=NewThread (show); Thread T2=NewThread (show); Thread T3=NewThread (show);        T.start ();        T1.start ();        T2.start ();    T3.start (); }}

This time to look at the results of the code, we will find that the repetition problem is missing, and the program is still switching between the threads, but the order of printing num is fixed and orderly, like a single-threaded loop 100 to 1, which is the thread of security problems, in fact, the problem is very simple to solve, is to add a synchronized block outside the code that needs to determine and change the value, he will make a decision when your thread enters the block, if there is a thread that is using the method, if any, it will intercept the thread, The thread is not run until the thread that is using the Synchronized method loses execution. No threads are used, threads are executed and threads are locked. You need to be aware of the deadlock problem when using synchronized.

Black Horse Programmer "multithreading 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.