67,513
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.locks.*;
public class T3 {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
PrintThread pt = new PrintThread(lock);
Thread t = new Thread(pt);
t.start();
}
}
class PrintThread implements Runnable {
ReentrantLock lock;
Condition condition;
PrintThread1 pt1;
Thread t1;
public PrintThread(ReentrantLock lock) {
this.lock = lock;
condition = lock.newCondition();
pt1 = new PrintThread1(lock, condition);
t1 = new Thread(pt1);
}
public void run() {
t1.start();
for (int i = 3; i >= 0; i--) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(i + "....");
if (i == 1) {
System.out.println("起床啦");
lock.lock();
try {
condition.signal();
} finally {
lock.unlock();
}
}
}
}
}
class PrintThread1 implements Runnable {
ReentrantLock lock;
Condition condition;
public PrintThread1(ReentrantLock lock, Condition condition) {
this.lock = lock;
this.condition = condition;
}
public void run() {
lock.lock();
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
System.out.println("复活了~");
}
}