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 the output, you will see that the variable x is operated by two threads at the same time. This makes it very easy to cause misoperation.

How can we solve the problem? Synchronization technology with threads. Plus Synchronizedkeyword.

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

Suppose the fix method added to the Testobj class can be synchronized?

public class Testobj{int x = 10;public synchronized int fix (int y) {return x = x-y;}}
Assuming that synchronized is added to a method is equivalent to

Synchronized (this) {}
It is possible to infer that the same instance of the Testobj class used by two threads is TESTOJB, so the output is not the desired result. This is because when a thread finishes running x = x-Y and there is no output then the B thread has entered start running 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;}}
Assume that the external fix method changes such as the following:

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 achieve mutual exclusion between threads.

What is a deadlock? For example, you and your classmates rented a two-room house, and you took the key to your house. Your classmate holding the key to his house, now you are in the house waiting for your classmate to give his key to you then you enter his house. Your classmates in his house waiting for you to give him the keys and then he went into your house, so that the deadlock.

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!                ");                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, rest 0.5 seconds after the 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 (); }}






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

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.