Android Multithreading Research (3) thread synchronization and mutex and deadlock

Source: Internet
Author: User
Tags mutex thread

Why is the concept of thread synchronization? Why sync? What is thread synchronization? First look at a piece of code:

Package com.maso.test;  
          
    public class ThreadTest2 implements runnable{private testobj testobj = new Testobj ();  
        public static void Main (string[] args) {ThreadTest2 tt = new ThreadTest2 ();  
        thread T1 = new Thread (TT, "thread_1");  
        Thread t2 = new Thread (TT, "thread_2");  
        T1.start ();  
    T2.start (); @Override public void Run () {for (int j = 0; J < J + +) {in  
            t i = fix (1);  
            try {thread.sleep (1);  
            catch (Interruptedexception e) {e.printstacktrace ();  
        } System.out.println (Thread.CurrentThread (). GetName () + ": i =" + i);  
    ' public int ' fix (int y) {return testobj.fix (y);  
              
        public class testobj{int x = 10; public int fix (intY) {return x = x-y; }  
    }  
          
          
}

When you output the result, you will find that the variable x is operated concurrently by two threads, which can easily lead to misoperation. How can we solve this problem? With thread synchronization technology, plus synchronized keyword

public synchronized int fix (int y) {

return Testobj.fix (y);

}

Coupled with synchronization, you can see an orderly output from 9 to-10.

If the fix method added to the Testobj class can achieve synchronization?

public class testobj{

int x = 10;

public synchronized int fix (int y) {

return x = x-y;

}

}

If you add synchronized to a method, it is equivalent to

Synchronized (this) {

}

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.