Android multithreaded Research (3)--thread synchronization and mutual exclusion and deadlock

Source: Internet
Author: User

Why is the concept of thread synchronization? Why synchronize? What is thread synchronization? Look at the code first:

Package Com.maso.test;public class ThreadTest2 implements runnable{private testobj testobj = new Testobj ();p ublic Static V OID 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 ();} @Overridepublic void Run () {for (int j = 0; J <; J + +) {int i = fix (1); try {thread.sleep (1);} catch (Interruptedexcepti On 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 (int y) {return x = x-y;}}}
After outputting the result, it is found that the variable x is manipulated by two threads at the same time, which can easily lead to mis-operation. How can we solve this problem? With the thread synchronization technology, plus the SYNCHRONIZED keyword

public synchronized int fix (int y) {return testobj.fix (y);}
With synchronization, you can see an ordered output from 9 to-10.

If you add to the fix method of the Testobj class, can synchronization be implemented?

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) {}
It is possible to determine the same instance TESTOJB of the Testobj class used by two threads, so the synchronization is implemented, but the output is not the desired result. This is because when a thread finishes executing x = x-Y and there is no output then the B thread has entered to start execution x = x-Y.

So there's no problem with the output like this:

public class Testobj{public Testobj () {System.out.println ("called Constructor");} int x = 10;public synchronized int fix (int y) {x = x = y; System.out.println (Thread.CurrentThread (). GetName () + ":  x =" + x); return x;}}
If the external fix method is modified as follows:

public int fix (int y) {ax++; if (ax%2 = = 0) {return Testobj.fix (y, testobj.str1);} Else{return Testobj.fix (y, TESTOBJ.STR2);}}
public class Testobj{string str1 = "A1"; String str2 = "A2";p ublic Testobj () {System.out.println ("constructor called");} int x = 10;public int fix (int y, String str) {synchronized (str) {x = XY; System.out.println (Thread.CurrentThread (). GetName () + ":  x =" + x);} return x;}}
The Str object in synchronized is not the same object, so the object locks held by two threads are not the same, so synchronization is not possible. The same object lock is used to implement mutual exclusion between threads.

What is a deadlock? For example, you and your classmates rented a two-room house, you hold the key to your house, your classmate holding the key of his house, now you in the house waiting for your classmate will his key to you then you enter his house, your classmates in his house waiting for you to give him the key and then he went into your house, so it is dead locked.

Package Com.maso.test;public class Threaddiesock implements Runnable {private int flag = 1;    Private Object obj1 = new Object (), Obj2 = new Object ();        public void Run () {System.out.println ("flag=" + flag); if (flag = = 1) {synchronized (obj1) {System.out.println ("I have locked obj1, rest 0.5 seconds after locking obj2 go!                ");                try {thread.sleep (500);                } catch (Interruptedexception e) {e.printstacktrace ();                } synchronized (OBJ2) {System.out.println ("1"); }}} if (flag = = 0) {synchronized (OBJ2) {System.out.println ("I have locked O Bj2, after 0.5 seconds of rest lock obj1 Go!                ");                try {thread.sleep (500);                } catch (Interruptedexception e) {e.printstacktrace ();    } synchronized (obj1) {System.out.println ("0");            }}}} public static void Main (string[] args) {Threaddiesock Run01 = new thre        Addiesock ();        Threaddiesock run02 = new Threaddiesock ();        Run01.flag = 1;        Run02.flag = 0;        Thread thread01 = new Thread (RUN01);        Thread thread02 = new Thread (RUN02); SYSTEM.OUT.PRINTLN ("Thread started!")        ");        Thread01.start ();    Thread02.start (); }}





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.