题目:开启两个线程,每个线程相隔往数组装数据,数组长度为6:
package itcast;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo20 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int [] arr=new int[6];
ArrayAdd array=new ArrayAdd(arr);
new Thread(array).start();
new Thread(array).start();
}
}
class ArrayAdd implements Runnable
{
private int[] in;
private int num=0;
private Random ra=new Random();
private ReentrantLock lock=new ReentrantLock();
Condition con= lock.newCondition();
/**
* @param in
*/
public ArrayAdd(int[] in) {
super();
this.in = in;
}
public void run(){
while(num<in.length){//判断添加的数组数量是否小于数组长度
lock.lock();//线程拿到锁
con.signal();//线程进来后,唤醒其他线程
if(num<in.length){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
int a=(ra.nextInt(20)+1);//随机生成的数
in[num]=a;
System.out.println(Thread.currentThread().getName()+":"+a);
num++;
try {
con.await();//调用await,放弃执行权
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
//lock.unlock();//想了想,这个锁就不用释放了,await已经释放执行权并释放了锁
}
}
}
}
}
|
|