> Java > java지도 시간 > 본문

Java의 멀티스레드 기아 현상에 대한 문제와 해결책

零下一度
풀어 주다: 2017-06-17 11:37:01
원래의
2499명이 탐색했습니다.

이 글은 주로 자바 멀티스레드 기아 문제에 대한 해결책 관련 정보를 소개합니다. 필요한 친구들이 참고하면 됩니다.

자바 멀티스레드 기아 문제에 대한 해결책

스레드가 읽기, 아니요 쓰기 스레드의 쓰기는 허용하지만 다른 읽기 스레드의 읽기는 허용합니다. 쓰기 스레드가 쓰는 동안 다른 스레드는 읽거나 쓸 수 없습니다. 쓰기 스레드가 고갈되는 것을 방지하기 위해 스레드가 읽을 때 쓰기 스레드가 쓰기를 요청하면 후속 읽기 스레드는 읽기를 금지해야 합니다.

구현 코드는 다음과 같습니다.

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(); 
     
      
      
  } 
      
       
   
     
     
  } 
   
 
}
로그인 후 복사

작가 .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(); 
   
 
} 
 
 
 
 
  } 
 
}
로그인 후 복사

프로그램 부분 실행 결과는 다음과 같습니다.


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....
로그인 후 복사

위 내용은 Java의 멀티스레드 기아 현상에 대한 문제와 해결책의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!