????? Java????????????
???????????? ???????[ 2013/12/23 11:01:31 ] ????????
?????
WorkerTwo:setp into critical section
WorkerTwo:call sayHello()
WorkerOne:step into critical section
????2??????????Condition??????wait-notify????????????????????????condition?е???-????????await()??signal()??signalAll()??????????????±????á?
(1) ??????
????Condition????Condition???????Lock???????????
Lock locker = new ReentrantLock();
Condition cond = locker.newCondition();
???????????????????С?
void await();
?????????????????????????????????
void signalAll();
?????????????????????????????????????????
void signal();
(2) ???????????
//????ok_to_proceed?false.
locker.lock()
try{
while(!ok_to_proceed){
//???????????????У??????????????????????????????????????????
//signalAll/signal?????????
cond.await();
}
}finally{
cker.unlock();
}
locker.lock();
try{
//???y???????е?????????μ????????????????????????б???????????????γ???????е????????????μ???????
//??????????????????????????????????????е??????????await???÷??????????????????????????????????С?
ok_to_proceed = true;
cond.signalAll() or cond.signal();
}finally{
locker.unlock();
}
ok_to_proceed????????wait-notify?????????????wait???notify()??????????????wait??????????????????????signal()????????await()?????????
(3) ???????
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class GlobalV{
public final static Lock locker = new ReentrantLock();
public final static Condition cond = locker.newCondition();
public static boolean to_proceed = false;
}
class Response extends Thread{
public void run(){
while(true){
GlobalV.locker.lock();
try{
while(!GlobalV.to_proceed){
GlobalV.cond.await();
}
System.out.println("Response:finish a job");
GlobalV.to_proceed = false;
}catch(Exception e){
e.printStackTrace();
}finally{
GlobalV.locker.unlock();
}
}
}
}
class Request extends Thread{
public void run(){
while(true){
GlobalV.locker.lock();
try{
GlobalV.to_proceed = true;
GlobalV.cond.signalAll();
System.out.println("Request:send a job to Response");
}finally{
GlobalV.locker.unlock();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Test6 {
public static void main(String[] args) {
Request req = new Request();
Response res = new Response();
req.start();
res.start();
}
}
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11