Multithreading in Android (3) -- thread synchronization and mutex and deadlock

Source: Internet
Author: User

Why is there a thread synchronization concept? Why synchronization? 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();}@Overridepublic void run() {for(int j = 0; j < 10; j++){int 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(int y){return x = x - y;}}}
After the result is output, the variable x is operated by two threads at the same time, which can easily lead to misoperations. How can this problem be solved? Use the thread synchronization technology and the synchronized keyword

public synchronized int fix(int y){return testObj.fix(y);}
After synchronization, we can see the ordered output from 9 to-10.

What if the fix method added to the TestObj class cannot be synchronized?

public class TestObj{int x = 10;public synchronized int fix(int y){return x = x - y;}}
Adding synchronized to a method is equivalent

synchronized(this){}
We can determine the same instance testOjb of the TestObj class used by two threads, so the subsequent implementation is synchronous, but the output results are not ideal. This is because when thread A has not output x = x-y, thread B has started to execute x = x-y.

So there will be no problem with the output like below:

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 you modify the external fix method 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"; public TestObj () {System. out. println ("called constructor");} int x = 10; public int fix (int y, String str) {synchronized (str) {x = x-y; System. out. println (Thread. currentThread (). getName () + ": x =" + x) ;}return x ;}}
In this case, the str object in synchronized is not the same object, so the two threads do not hold the same object lock, so synchronization cannot be implemented. To achieve mutual exclusion between threads, you must use the same object lock.

What is deadlock? For example, if you and your classmates rent a two-room house, you hold the key of your house, and your classmates hold the key of his house, now you are waiting for your classmates to give you his key and then you enter his house. Your classmates wait for you to give him the key in his house and then he enters your house, in this way, the deadlock occurs.

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, And I will lock obj2 after 0.5 seconds of rest! "); 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 obj2, And I will lock obj1 after 0.5 seconds of rest! "); Try {Thread. sleep (500);} catch (InterruptedException e) {e. printStackTrace ();} synchronized (obj1) {System. out. println ("0") ;}}} public static void main (String [] args) {ThreadDieSock run01 = new ThreadDieSock (); 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 ();}}





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.