<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    ゞ沉默是金ゞ

    魚離不開水,但是沒有說不離開哪滴水.
    posts - 98,comments - 104,trackbacks - 0
    Today in next part of the series we will talk about How to communicate among threads using Lock and Condition Objects.


    In traditional Java - If we need to communicate among threads, we syncronize code and use "wait" and "notify" methods  of Object class.
    From Java 5.0 and above - Lock interface provides an easier implmentation for synchronization and Condition class can be used to wait and notify threads.


    Lock has several important methods such as "lock", "tryLock", "lockInterruptibly" etc, whereas Condition has "await", "signal", 'signalAll" etc. In this article we will demonstrate the usage of 3 methods - "lock" (from Lock interface), "await", "signal" (from Condition Class).


    Lets try to visualize a scenario here - Assume we have 2 process "Reader" and "Writer". Writer writes on a file and Reader reads from a file. we want to add a listener to writer object so that whenever writer writes anything on a file, "Reader" will be called and it will read the same data. Before we look into codes lets look at the some important points to use Lock and Condition-


    1) Lock is an Interface, the most common implementation class is ReentrantLock. Others two are - ReentrantReadWriteLock.ReadLock, ReentrantReadWriteLock.WriteLock
    2) Condition Object is always retrieved from Lock object. For example - Condition condition = lock.newCondition( );
    3) One of the best practice to use Lock is-
    Lock lockObj = new ReentrantLock( );
                        lockObj.lock( );
                            try{
    .... code..
                               }finally{
                          lockObj.unlock( );
                               }
    4) condition.await, condition.signal, condition.signalAll methods should only be called once you have acquired the lock by - lockObj.lock( ).
    In our example, the design of the class will be something like this -
    > One lock Object == fileLock
    > One condition Object = condition = fileLock.newCondition


    Pseudo code for Writer Thread 
    // GET the LOCK
    try{
      // -- In  the Loop untill EXIT---
         //Write on the file
         // Signal the READER
         //If EXIT signal then exit else "WAIT for READER to SIGNAL"
     }finally{
      // RELEASE the LOCK
     }
    pseudo code for Reader Thread 
    // GET the LOCK
    try{
      // -- In  the Loop untill EXIT---
         //Read from the file
         // Signal the WRITER
         // If EXIT signal - then exit else "WAIT for WRITER to SIGNAL"
     }finally{
      // RELEASE the LOCK
     }


    package com.jovialjava.blog.threads;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.PrintWriter;
    import java.security.SecureRandom;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;

    public class LockExample {

        
    private static final String fileName = "LockExample.txt";
        
    private static final String EXIT_FLAG = "BYE";
        
    private static final int NO_OF_LINES = 10;
        
    private static final Lock fileLock = new ReentrantLock();
        
    private static final Condition condition = fileLock.newCondition();
        
    private static final ExecutorService executorPool = Executors.newFixedThreadPool(2);

        
    public static void main(String args) {
            Runnable fileWriter 
    = new FileWrite();
            Runnable fileReader 
    = new FileRead();
            executorPool.submit(fileReader);
            executorPool.submit(fileWriter);
            executorPool.shutdown();
        }

        
    /**
         * This thread will write on a file and inform the reader thread to read it.
         * If it has not written the EXIT flag then it will go into wait stage and
         * will wait for READER to signal that it safe to write now.
         
    */
        
    public static class FileWrite implements Runnable {

            
    public void run() {
                
    try {
                    fileLock.lock();
                    
    for (int i = 0; i < NO_OF_LINES; i++) {
                        PrintWriter writer 
    = new PrintWriter(new File(fileName));
                        
    if (i != NO_OF_LINES - 1) {
                            
    int random = new SecureRandom().nextInt();
                            System.out.println(
    "WRITER WRITING " + random);
                            writer.println(random);
                            writer.close();
                            
    // signallng to READER that its safe to read now.
                            condition.signal();
                            System.out.println(
    "Writer waiting");
                            condition.await();
                        } 
    else {
                            writer.println(EXIT_FLAG);
                            System.out.println(
    "WRITER EXITING ");
                            writer.close();
                            
    // AS it was an exit flag so no need to wait, just
                            
    // signal the reader.
                            condition.signal();
                        }
                    }
                } 
    catch (Exception e) {
                    System.out.println(
    "!!!!!!!!!!!!!!!!!!!!!!!!EXCEPTION!!!!!!!!!!!!!!!!!!!!!!!!");
                    e.printStackTrace();
                } 
    finally {
                    fileLock.unlock();
                    
    // Delete the file, require in case if one wants to run demo
                    
    // again.
                    File file = new File(fileName);
                    file.delete();
                    
    try {
                        file.createNewFile();
                    } 
    catch (Exception e) {
                    }
                }
            }
        }

        
    /**
         * This thread will read from the file and inform the writer thread to write
         * again. If it has not read the EXIT flag then it will go into wait stage
         * and will wait for WRITER to signal that it safe to read now.
         
    */
        
    public static class FileRead implements Runnable {

            
    public void run() {
                String data 
    = null;
                fileLock.lock();
                
    try {
                    
    while (true) {
                        BufferedReader reader 
    = new BufferedReader(new FileReader(fileName));
                        data 
    = reader.readLine();
                        System.out.println(
    "READ DATA - " + data);
                        reader.close();
                        
    if (data == null || !data.equals(EXIT_FLAG)) {
                            condition.signalAll();
                            System.out.println(
    "Reader Waiting");
                            condition.await();
                        } 
    else {
                            System.out.println(
    "READER EXITING");
                            condition.signal();
                            
    break;
                        }
                    }
                } 
    catch (Exception e) {
                    System.out.println(
    "!!!!!!!!!!!!!!!!!!!!!!!!EXCEPTION!!!!!!!!!!!!!!!!!!!!!!!!");
                    e.printStackTrace();
                } 
    finally {
                    fileLock.unlock();
                }
            }
        }
    }
    posted on 2012-08-06 10:38 ゞ沉默是金ゞ 閱讀(785) 評論(0)  編輯  收藏 所屬分類: Java SE
    主站蜘蛛池模板: 西西大胆无码视频免费| 无码精品国产一区二区三区免费| 久久亚洲精品中文字幕三区| 精品在线观看免费| 免费国产综合视频在线看 | 一级a性色生活片久久无少妇一级婬片免费放 | 亚洲娇小性色xxxx| 无码中文字幕av免费放| va天堂va亚洲va影视中文字幕| 国产精品成人免费福利| 亚洲人成网站18禁止久久影院| 免费能直接在线观看黄的视频 | 久久久久久99av无码免费网站| 亚洲精品伊人久久久久| 日韩特黄特色大片免费视频| 国产亚洲美女精品久久| 国产亚洲情侣一区二区无码AV| 两个人看的www高清免费观看| 久久久亚洲精品无码| 精品免费久久久久久久| 亚洲综合无码一区二区痴汉 | 成年女人毛片免费观看97| 国产亚洲成av片在线观看 | 亚洲中文字幕无码爆乳app| 国产成人涩涩涩视频在线观看免费| 免费观看亚洲人成网站| 亚洲精品蜜桃久久久久久| 久久九九兔免费精品6| 亚洲日韩看片无码电影| 精品亚洲一区二区三区在线播放| 香港a毛片免费观看| 亚洲国产aⅴ成人精品无吗| 在线看免费观看AV深夜影院| 亚洲国产精品ⅴa在线观看| 久久久久亚洲精品中文字幕| 中国人xxxxx69免费视频| 老司机亚洲精品影院在线观看| 亚洲熟妇无码AV在线播放| 中文字幕影片免费在线观看| 美景之屋4在线未删减免费 | 99久久综合国产精品免费|