<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级成人毛片免费图片| 亚洲欧美日韩中文字幕一区二区三区| 无码的免费不卡毛片视频| 四虎在线免费播放| 中文字幕乱码亚洲精品一区| 曰曰鲁夜夜免费播放视频 | 亚洲精品偷拍视频免费观看 | 日韩视频免费在线| 亚洲一区二区三区高清在线观看| 手机在线免费视频| 欧洲 亚洲 国产图片综合| 无码日韩精品一区二区免费| 国产99在线|亚洲| 成年女人免费视频播放77777 | 亚洲第一成年免费网站| 亚洲人xxx日本人18| 情侣视频精品免费的国产| 国产在亚洲线视频观看| 亚洲AV无码乱码在线观看| a一级爱做片免费| 久热综合在线亚洲精品| 午夜免费1000部| 亚洲AV无码专区在线电影成人| 免费大片黄手机在线观看| 国产精品小视频免费无限app| 亚洲国产精品无码av| 免费视频爱爱太爽了| 香蕉视频亚洲一级| 亚洲人成网站18禁止一区| 无码国产精品一区二区免费16| 亚洲国产中文在线二区三区免| 日韩一品在线播放视频一品免费| 一级午夜a毛片免费视频| 亚洲精选在线观看| 在线A级毛片无码免费真人| 老司机精品免费视频| 亚洲电影在线免费观看| 国产三级免费电影| 久久国产精品成人免费| 一区二区亚洲精品精华液| 最新亚洲成av人免费看|