package com.wa.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @Author:wangxin
* @Date:2018/3/19
* @version:1.0.0
*/
public class TestQueue {
public static void main(String args[]) throws InterruptedException {
final Lock lock = new ReentrantLock();
final Condition condition = lock.newCondition();
final Condition condition1 = lock.newCondition();
final List<Integer> list = new ArrayList<Integer>(10);
for(int i =0;i<9;i++){
list.add(i);
}
Thread thread = new Thread(new Runnable() {
public void run() {
for(int i=0;i<9;i++) {
lock.tryLock();
lock.lock();
condition.signal();
System.out.println("1:" + list.get(i));
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread thread1 = new Thread(new Runnable() {
public void run() {
for(int i=0;i<9;i++) {
lock.lock();
try {
condition.await();
System.out.println("2:" + list.get(i));
condition1.signal();
lock.tryLock();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
}
}
}
});
thread1.start();
thread.start();
}
}
网友评论