a- package test;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- public class Test2 {
- public static void main(String[] args) throws Exception{
- final P p = new P();
- new Thread() {
- public void run() {
- for (int i = 1; i < 11; i++) {
- p.show(i);
- }
- };
- }.start();
- new Thread() {
- public void run() {
- for (int i = 1; i < 11; i++) {
- p.print(i);
- }
- };
- }.start();
- }
- }
- class P {
- boolean flag = false;
- Lock l = new ReentrantLock();
- Condition con = l.newCondition();
- public void show(int i) {
- l.lock();
- try{
- while(flag)
- try {
- con.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(i + "..." + Thread.currentThread().getName());
- flag = true;
- }
- finally{
- con.signalAll();
- l.unlock();
- }
- }
- public void print(int i) {
- l.lock();
- try{
- while(!flag)
- try {
- con.await();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(i + "..." + Thread.currentThread().getName());
- flag = false;
- }
- finally{
- con.signalAll();
- l.unlock();
- }
- }
- }
复制代码
|
|