没写注释,自己看看吧,我也捣鼓了好久才弄懂的。- import java.util.Random;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- /*声明一个共享数组,起两个线程,两个线程分别隔一段时间(可以写一个随机数),给数组中添加数据,每一个线程为数组添加3个数据即可。*/
- public class TwoThreadToArray {
- public static void main(String[] args) {
- final Rec2 r=new Rec2();
- Thread t1=new Thread(new Runnable(){
- public void run()
- {
- for(int x=0;x<3;x++)
- {
- r.addFirst(x,r.num++);
- }
- }
- },"w1");
-
- Thread t2=new Thread(new Runnable(){
- public void run()
- {
- for(int x=0;x<3;x++)
- {
- r.addSecond(x,r.num++);
- }
- }
- },"w2");
- t1.start();
- t2.start();
-
- try {t1.join(); } catch (InterruptedException e) {e.printStackTrace();}
- try {t2.join(); } catch (InterruptedException e) {e.printStackTrace();}
- System.out.println("--------------");
- for(int i=0;i<r.arr.length;i++)
- {
- System.out.println("arr["+i+"]="+r.arr[i]);
- }
- }
-
- }
- class Rec2
- {
- int[] arr=new int[6];
- boolean flag;
- int num;
- Lock lock=new ReentrantLock();
- Condition conditon_fr=lock.newCondition();
- Condition conditon_se=lock.newCondition();
-
- public void addFirst(int x,int num) {
- lock.lock();
- try{
- while(flag)
- {
- conditon_fr.await();
- }
- Thread.sleep(100);
- arr[num]=new Random().nextInt(10);
- System.out.println(Thread.currentThread().getName()+"first--"+"arr["+num+"]"+arr[num]);
- flag=true;
- conditon_se.signal();
- }
- catch(Exception e)
- {
-
- }
- finally
- {
- lock.unlock();
- }
- }
- public void addSecond(int x,int num) {
- lock.lock();
- try{
- while(!flag)
- {
- conditon_se.await();
- }
- Thread.sleep(100);
- arr[num]=new Random().nextInt(10);
- System.out.println(Thread.currentThread().getName()+"second--"+"arr["+num+"]"+arr[num]);
- flag=false;
- conditon_fr.signal();
- }
- catch(Exception e)
- {
-
- }
- finally
- {
- lock.unlock();
- }
- }
- }
复制代码
|