创建两个并发线程,一个是读线程,另一个是写线程。这两个线程共享一个数组A,写线程对数组分别进行10次写操作,每次写操作对A的每个元素赋一个相同的值;读线程对数组分别进行10次读操作,每次读操作输出A中所有元素的值。修改代码,使每次读写互斥,即每次对数组的写操作结束后才能进行写操作,反之亦然。

解决方案 »

  1.   

    int i[]=new int[10];
    void write(int w){
     synchronized(i){
        int j=9;
         while(j-->=0){
            a[j]=w;
          }
      }
    }
    ------------------------------
    int i[]=new int[10];
    synchronized void write(int w){
        int j=9;
         while(j-->=0){
            a[j]=w;
          }
      
    }
      

  2.   

    class MyThread
    {
    public static void main(String [] args)
    {
    PutGet t = new PutGet();
    new Thread(new Product(t)).start();
    new Thread(new Consumer(t)).start();
    }
    }
    class PutGet
    {
    private String name;
    private String sex;
    boolean b=false;
    public void put(String name,String sex)
    {
      if(b)
      try{wait();}catch(Exception e){}
    this.name=name;
    this.sex=sex;
    b=true;
     try{notify();}catch(Exception e){}
    }
    public void get()
    {
    if(!b)
      try{wait();}catch(Exception e){}
    System.out.println(name+"-----"+sex);
    b=false;
        try{notify();}catch(Exception e){}
    }
    }
    class Product implements Runnable
    {
    PutGet q=null;
    int i=0;
    public Product(PutGet q)
    {
    this.q=q;
    }
    public void run()
    {

    while(true)
    {
    synchronized(q)
    {

    if(i==0)
    {
       q.put("利","男");
       i=(i+1)%2;
     }
    else
       {
        q.put("静","女");
        i=(i+1)%2;
        }
     
    }
    }
    }
    }
    class Consumer implements Runnable
    {
    PutGet q=null;

    public Consumer(PutGet q)
    {
    this.q=q;
    }
    public void run()
    {
    while(true)
    {
    synchronized(q)
    {
     q.get();
        
    }
    }
    }
    }
      

  3.   

    初时运行是,读线程等待(wait),写线程工作,工作完毕,notify,然后wait
    写线程被唤醒后工作,工作完毕,notify,然后wait
    就这样。