Maison  >  Article  >  Java  >  Problèmes et solutions au phénomène de famine multithread en Java

Problèmes et solutions au phénomène de famine multithread en Java

零下一度
零下一度original
2017-06-17 11:37:012497parcourir

Cet article présente principalement des informations pertinentes sur la façon de résoudre le problème de la famine multithread Java. Les amis qui en ont besoin peuvent s'y référer

Comment résoudre le problème de la famine multithread Java.

Lorsqu'un fil est en train de lire, le fil d'écriture n'est pas autorisé à écrire, mais les autres fils de lecture sont autorisés à lire. Pendant qu'un thread d'écriture est en train d'écrire, les autres threads ne doivent ni lire ni écrire. Afin d'éviter que le thread d'écriture ne meure de faim, lorsque le thread est en train de lire, si le thread d'écriture demande à écrire, le thread de lecture suivant doit être interdit de lire.

Le code d'implémentation est le suivant :

File.Java


package readerWriter; 
 
public class File { 
private String name; 
public File(String name) 
{ 
  this.name=name; 
   
} 
}

Pool.java


package readerWriter; 
 
public class Pool { 
private int readerNumber=0; 
private int writerNumber=0; 
private boolean waittingWriten; 
 
public boolean isWaittingWriten() { 
  return waittingWriten; 
} 
public void setWaittingWriten(boolean waittingWriten) { 
  this.waittingWriten = waittingWriten; 
} 
 
 
 
public File getFile() { 
  return file; 
} 
public void setFile(File file) { 
  this.file = file; 
} 
File file; 
public Pool(File file) 
{ 
  this.file=file; 
 
} 
public int getReaderNumber() { 
  return readerNumber; 
} 
public void setReaderNumber(int readerNumber) { 
  this.readerNumber = readerNumber; 
} 
public int getWriterNumber() { 
  return writerNumber; 
} 
public void setWriterNumber(int writerNumber) { 
  this.writerNumber = writerNumber; 
} 
 
}

Reader.java


package readerWriter; 
 
public class Reader implements Runnable{ 
   
  private String id; 
  private Pool pool; 
   
   
  public Reader(String id,Pool pool) 
  { 
    this.id=id; 
    this.pool=pool; 
  } 
   
   
  @Override 
  public void run() 
  { 
    // TODO Auto-generated method stub 
    while(!Thread.currentThread().interrupted()){ 
       
    synchronized(pool){ 
       
        while(pool.getWriterNumber()>0 || pool.isWaittingWriten()==true)//当线程正在写或者 
                                        //有线程正在等待写,则禁止读线程继续读  
        { 
           
             
              try { 
                pool.wait(); 
              } catch (InterruptedException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
              } 
             
           
           
        } 
       
      { 
         
        pool.setReaderNumber(pool.getReaderNumber()+1);  
          
         
      } 
    } 
     System.out.println(id+" "+"is reading...."); 
      
     try { 
      Thread.sleep(1000); 
    } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
   
    synchronized(pool) 
    { 
      pool.setReaderNumber(pool.getReaderNumber()-1);  
      System.out.println(id+"  "+"is existing the reader...."); 
      if(pool.getReaderNumber()==0) 
          pool.notifyAll(); 
    } try { 
      Thread.sleep(1000); 
    } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
    // pool.notifyAll(); 
     
      
      
  } 
      
       
   
     
     
  } 
   
 
}

Writer.java


package readerWriter; 
 
public class Writer implements Runnable{ 
  private Pool pool; 
  String id; 
  public Writer(String id,Pool pool) 
  { 
    this.id=id; 
    this.pool=pool; 
     
     
  } 
  @Override 
  public void run() { 
    // TODO Auto-generated method stub 
    while(!Thread.currentThread().interrupted()){ 
       
    synchronized(pool){ 
      if(pool.getReaderNumber()>0) 
        pool.setWaittingWriten(true); 
      else 
        pool.setWaittingWriten(false); 
     
      //当线程正在被读或者被写或者有线程等待读 
       
        while(pool.getWriterNumber()>0 ||  pool.getReaderNumber()>0)   
        { 
          try { 
            pool.wait();   
          } catch (InterruptedException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
          } 
           
        } 
      pool.setWaittingWriten(false);  //这个策略还算公平 
      { 
         
        pool.setWriterNumber(pool.getWriterNumber()+1); 
          
         
      } 
    } 
     System.out.println(id+" "+"is writing...."); 
 
     try { 
      Thread.sleep(1000); 
    } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
    } 
      
     // 
    synchronized(pool) 
    { 
       
      pool.setWriterNumber(pool.getWriterNumber()-1); 
      System.out.println(id+"  "+"is existing the writer...."); 
      pool.notifyAll(); 
    } 
     /* try { 
        Thread.sleep(1000); 
        //System.out.println("writer sleeping over"); 
      } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
      } */ 
     
      
      
  } 
 
} 
}

Main.java


package readerWriter; 
 
public class Main { 
 
  public static void main(String[] args) { 
    // TODO Auto-generated method stub 
Pool pool=new Pool(new File("dd file")); 
for(int i=0;i<2;i++) 
{ 
 Thread writer=new Thread(new Writer("writer "+i,pool)); 
 writer.start(); 
} 
for(int i=0;i<5;i++) 
{ 
   
  Thread reader=new Thread(new Reader("reader "+i,pool)); 
  reader.start(); 
   
 
} 
 
 
 
 
  } 
 
}

Les résultats de l'exécution d'une partie du programme sont les suivants :


writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
reader 0 is reading.... 
reader 0  is existing the reader.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
reader 3 is reading.... 
reader 2 is reading.... 
reader 4 is reading.... 
reader 1 is reading.... 
reader 0 is reading.... 
reader 3  is existing the reader.... 
reader 1  is existing the reader.... 
reader 0  is existing the reader.... 
reader 4  is existing the reader.... 
reader 2  is existing the reader.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 1 is writing.... 
writer 1  is existing the writer.... 
reader 2 is reading.... 
reader 2  is existing the reader.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing.... 
writer 0  is existing the writer.... 
writer 0 is writing....

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn