Black Horse programmer [multithreading in Java], black horse java Multithreading

Source: Internet
Author: User

Black Horse programmer [multithreading in Java], black horse java Multithreading

Multithreading in Java

First, let's talk about a problem before talking about threads. We know that the principle of Multithreading is that the cpu performs switching operations in different threads, the first thing we think of is definitely to improve the system operation efficiency, but is it true? With the help of the Code in a blog, we can see that sometimes the running efficiency of a single thread is higher than that of multithreading:

import threadingfrom time import ctimeclass MyThread(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    for i in range(x):        y+=1def fun2(x):    y = 0    for i in range(x):        y+=1        def 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 that the running efficiency of a single thread is significantly higher than that of multiple threads. Why? Or because the thread execution principle is that the cpu performs fast switching between your threads, if you are a single-core cpu, then your program does not need to verify multithreading, because the switching between threads is performed under one cpu, only the dual-core or multi-core cpu can execute different threads with different CPUs to improve the program running efficiency. I believe that many people have experimented with the execution time of multiple threads on their computers and are confused about the results, because of your cpu usage.

Okay, I raised a small question. Now let's talk about the thread in java. There are two ways to create a Thread: one is to directly inherit the Thread class and overwrite its run () method, but we know that java only supports single inheritance, if our class has a parent class, it is difficult to implement this method. The second method is to implement the Runnable interface through declaration, then implement the run method, and then allocate instances of this class. when creating the Thread class, it is passed and started through the construction with parameters, runnable provides an activation method for non-Thread classes. The following code demonstrates the second thread creation method:

class Show implements Runnable {    private int num = 100;    @Override    public void run() {        while (true) {                if (num > 0) {                                        System.out.println(Thread.currentThread().getName()+":"+num);                    num--;                } else {                    break;                }                }    }}public class MyMain {    public static void main(String[] args) {        Show show = new Show();        Thread t = new Thread(show);        Thread t1 = new Thread(show);        Thread t2 = new Thread(show);        Thread t3 = new Thread(show);        t.start();        t1.start();        t2.start();        t3.start();    }}

In this way, four threads are executed at the same time until num sees 0. However, if we open the running result, we will find a very obvious problem:

This is a part of my running results. It can be obvious that 100 occurs four times. Why? Take this code for example. When your t thread obtains the execution right of the cpu, it executes the internal run method and enters the loop to determine the if condition and determines that num> 0 passes, enter the internal code block to print the num value, but at this time, another thread t1 obtains the execution right, and also enters the loop to determine the if condition. When num> 0 is passed, the value of num is not changed, but the value of num is still printed. In this case, two identical values are displayed. When there are multiple such values, there will be multiple repeated values, which is a thread security issue. That is, when multiple threads operate on the same variable at the same time, unpredictable results may occur. So how can we solve this problem? In this case, synchronized (synchronous function) is used to lock the thread, which is equivalent to no matter which thread (such as thread A) runs to this method, check whether other threads B (or C, D, etc.) are using this method (or other Synchronization Methods of this class ), if yes, wait until thread B (or C or D) using the synchronized method runs this method and then run thread A. If no, lock the caller and run it directly. It may be hard to understand. The following shows the modified version of the code above. Let's take a look at the running result:

class Show implements Runnable {    private int num = 100;    Object obj = new Object();    @Override    public void run() {        while (true) {            synchronized (obj) {                if (num > 0) {                                        System.out.println(Thread.currentThread().getName()+":"+num);                    num--;                } else {                    break;                }            }        }    }}public class MyMain {    public static void main(String[] args) {        Show show = new Show();        Thread t = new Thread(show);        Thread t1 = new Thread(show);        Thread t2 = new Thread(show);        Thread t3 = new Thread(show);        t.start();        t1.start();        t2.start();        t3.start();    }}

When we look at the code running results again this time, we will find that the duplicate problem just disappeared, and although the program still switches between various threads, however, the order of printed num is fixed and ordered, as in a single thread loop, which is 100 to 1. This is the thread security problem. In fact, the solution is very simple, the synchronized block is added to the code that needs to be determined and changed. It will make a decision when your thread enters the block. If there is a thread that is using this method, if yes, the thread will be intercepted until the thread using the synchronized Method loses the execution right. The execution thread is not used, and the thread is locked. Pay attention to the deadlock when using synchronized.

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.