WEB开发网      濠靛倻鏅悵顖涚附閽樺鐎诲ù婊庡亾缁辨帗鎷呴悩鍨暠濞戞挴鍋撳ù鐘烘閸ㄥ孩绂嶉锝喰﹂柟瀛樺灣濠婃垿鎯冮崟顏嗩伇濞寸姾妫勬慨鈺呭礉濞戝磭骞㈤悹鍥у槻閸ㄥ孩绂嶉敓锟� ---闁挎洩鎷�
开发学院软件开发Java 多线程设置模式 -- Read-Write Lock Pattern 阅读

多线程设置模式 -- Read-Write Lock Pattern

 2009-09-17 00:00:00 来源:WEB开发网 闁靛棴鎷�闁告垵绻愰惃顒傗偓娑欍仦缂嶏拷濠⒀呭仜閵囧洨鈧稒銇炵紞锟�闁靛棴鎷�  闁稿繗娅曢弫鐐哄级閵婏缚鑸瀣仧濞堟垵顕ラ鐓庤Е
核心提示: 读线程 Java代码publicclassReaderThreadextendsThread{privatefinalDatadata;publicReaderThread(Datadata){this.data=data;}publicvoidrun(){try{while(true){cha

读线程

Java代码   

public class ReaderThread extends Thread { 
  private final Data data; 
  public ReaderThread(Data data) { 
    this.data = data; 
  } 
  public void run() { 
    try { 
      while (true) { 
        char[] readbuf = data.read(); 
        System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readbuf)); 
      } 
    } catch (InterruptedException e) { 
    } 
  } 
}

写线程

Java代码   

public class WriterThread extends Thread { 
  private static final Random random = new Random(); 
  private final Data data; 
  private final String filler; 
  private int index = 0; 
  public WriterThread(Data data, String filler) { 
    this.data = data; 
    this.filler = filler; 
  } 
  public void run() { 
    try { 
      while (true) { 
        char c = nextchar(); 
        data.write(c); 
        Thread.sleep(random.nextInt(3000)); 
      } 
    } catch (InterruptedException e) { 
    } 
  } 
  private char nextchar() { 
    char c = filler.charAt(index); 
    index++; 
    if (index >= filler.length()) { 
      index = 0; 
    } 
    return c; 
  } 
}

上一页  1 2 3 4  下一页

Tags:线程 设置 模式

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接