Created
May 18, 2015 05:01
-
-
Save happycodinggirl/043ee9d87d7a32cc6562 to your computer and use it in GitHub Desktop.
测试ReentrantLock使用的代码。学习自:http://outofmemory.cn/java/java.util.concurrent/lock-reentrantlock-condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.huangxingli.testreentrantlock; | |
import android.util.Log; | |
import java.util.concurrent.locks.Condition; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReentrantLock; | |
/** | |
* Created by huangxingli on 2015/5/18. | |
*/ | |
public class MyTest { | |
final Lock mLock=new ReentrantLock(); | |
Condition wait3Condition=mLock.newCondition(); | |
Condition wait6Condition=mLock.newCondition(); | |
int printNum=1; | |
class Thread1 extends Thread{ | |
@Override | |
public void run() { | |
super.run(); | |
mLock.lock(); | |
while (printNum<=3){ | |
Log.v("TAG","---thread111-printNum is--"+printNum); | |
printNum++; | |
}; | |
wait3Condition.signal(); | |
try { | |
mLock.unlock(); | |
mLock.lock(); | |
wait6Condition.await(); | |
while (printNum<=9){ | |
Log.v("TAG","--thread11111==----printNum is---"+printNum); | |
printNum++; | |
} | |
mLock.unlock(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
class Thread2 extends Thread{ | |
@Override | |
public void run() { | |
super.run(); | |
mLock.lock(); | |
try { | |
while (printNum<=3) { | |
wait3Condition.await(); | |
} | |
mLock.unlock(); | |
mLock.lock(); | |
while(printNum<=6){ | |
Log.v("TAG","--thread2222---printNum is--"+printNum); | |
printNum++; | |
} | |
wait6Condition.signal(); | |
mLock.unlock(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
public void startWork(){ | |
Thread1 thread1=new Thread1(); | |
Thread2 thread2=new Thread2(); | |
thread1.start(); | |
thread2.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment